2010-10-11 215 views
7

如果我有像“C:\ My Documents \ Images \ Image1.png”文件路径,如何获取“Image1.png”文件的父文件夹名称?在这种情况下,“图像”,但这只是一个示例。我已经浏览了System.IO.Path,似乎没有任何东西。也许我忽略了它,但我不知道它会在哪里。从路径获取文件夹名称

回答

9

像这样:

Path.GetFileName(Path.GetDirectoryName(something)) 
+0

时髦的实例,我不知道你能解决这样的问题。 +1 – AndyPerfect 2010-10-11 23:42:36

+0

太棒了,这是最直接的。感谢名单! – Stan 2010-10-12 16:05:57

2

试试这个:

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

使用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; 
+0

该属性返回目录的完整路径,这不是他想要的。 – SLaks 2010-10-11 23:51:25

+0

感谢您指出 - 更新。 FileInfo.Directory.Name将返回所需的结果。 – code4life 2010-10-12 00:20:37

1

下面的方法将提取所有目录名和文件名

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

这是不必要的缓慢。 – SLaks 2010-10-11 23:50:42

+0

好吧,标题暗示了获取多个文件夹名称的可能性 - 并不确定提问者是否可能想要的不仅仅是一个父目录,那么为什么不呢? – AndyPerfect 2010-10-11 23:53:48

+0

您还应该在备用路径分隔符(/ for Windows)上进行拆分 – Joe 2010-10-12 08:24:55

4

创建

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