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.
Asked
Active
Viewed 5,952 times
7

Stan
- 746
- 1
- 17
- 35
6 Answers
12
Like this:
Path.GetFileName(Path.GetDirectoryName(something))

SLaks
- 868,454
- 176
- 1,908
- 1,964
-
Snazzy, I didn't know you could tackle the problem like this. +1 – AndyPerfect Oct 11 '10 at 23:42
-
Great, this is the most straightforward. Thanx! – Stan Oct 12 '10 at 16:05
5
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;

code4life
- 15,655
- 7
- 50
- 82
-
This property returns the full path to the directory, which is not what he wants. – SLaks Oct 11 '10 at 23:51
-
Thanks for pointing that out - updated. FileInfo.Directory.Name will return the desired result. – code4life Oct 12 '10 at 00:20
4
Create an instance of
System.IO.FileInfo f1 = new FileInfo("filepath");
DirectoryInfo dir=f1.Directory;
string dirName = dir.Name;
string fullDirPath = dir.FullName;

AsifQadri
- 2,388
- 1
- 20
- 30
2
Try this:
var directoryFullPath = Path.GetDirectoryName(@"C:\My Documents\Images\Image1.png");
var directoryName = Path.GetFileName(directoryFullPath); \\ Images

Leniel Maccaferri
- 100,159
- 46
- 371
- 480
1
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.

Community
- 1
- 1

Dave Anderson
- 11,836
- 3
- 58
- 79
1
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))

AndyPerfect
- 1,180
- 1
- 10
- 25
-
well, the title hints at the possibility of getting multiple folder names - wasn't sure if the asker may have wanted more than just the one parent directory, so why not? – AndyPerfect Oct 11 '10 at 23:53
-