Stan
Stan

Reputation: 746

Getting Folder Name(s) from Path

If I have a file path like "C:\My Documents\Images\Image1.png", how can I get the parent folder name of the "Image1.png" file? In this case, "Images", but that's just a sample. I've looked through System.IO.Path and there doesn't seem to be anything there. Maybe I'm overlooking it, but I have no idea where it would be.

Upvotes: 7

Views: 6283

Answers (6)

AsifQadri
AsifQadri

Reputation: 2389

Create an instance of

 System.IO.FileInfo f1 = new FileInfo("filepath");
                    DirectoryInfo dir=f1.Directory;
                    string dirName = dir.Name;
                    string fullDirPath = dir.FullName;

Upvotes: 4

code4life
code4life

Reputation: 15794

Use System.IO.FileInfo.

string fl = "C:\My Documents\Images\Image1.png";
System.IO.FileInfo fi = new System.IO.FileInfo(fl);
string owningDirectory = fi.Directory.Name;

Upvotes: 5

AndyPerfect
AndyPerfect

Reputation: 1180

The following method will extract all the directory names and file name

Dim path As String = "C:\My Documents\Images\Image1.png"
Dim list As String() = path.Split("\")
Console.WriteLine(list.ElementAt(list.Count - 2))

Upvotes: 1

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102458

Try this:

var directoryFullPath = Path.GetDirectoryName(@"C:\My Documents\Images\Image1.png");
var directoryName = Path.GetFileName(directoryFullPath);  \\ Images

Upvotes: 2

Dave Anderson
Dave Anderson

Reputation: 12324

Have a look at this answer; C# How do I extract each folder name from a path? and then just go for the last element in the array.

Upvotes: 1

SLaks
SLaks

Reputation: 888283

Like this:

Path.GetFileName(Path.GetDirectoryName(something))

Upvotes: 12

Related Questions