【发布时间】:2010-10-12 18:42:15
【问题描述】:
如果我有像“C:\My Documents\Images\Image1.png”这样的文件路径,如何获取“Image1.png”文件的父文件夹名称?在这种情况下,“图像”,但这只是一个示例。我浏览了System.IO.Path,似乎没有任何东西。也许我忽略了它,但我不知道它会在哪里。
【问题讨论】:
如果我有像“C:\My Documents\Images\Image1.png”这样的文件路径,如何获取“Image1.png”文件的父文件夹名称?在这种情况下,“图像”,但这只是一个示例。我浏览了System.IO.Path,似乎没有任何东西。也许我忽略了它,但我不知道它会在哪里。
【问题讨论】:
像这样:
Path.GetFileName(Path.GetDirectoryName(something))
【讨论】:
使用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;
【讨论】:
创建一个实例
System.IO.FileInfo f1 = new FileInfo("filepath");
DirectoryInfo dir=f1.Directory;
string dirName = dir.Name;
string fullDirPath = dir.FullName;
【讨论】:
试试这个:
var directoryFullPath = Path.GetDirectoryName(@"C:\My Documents\Images\Image1.png");
var directoryName = Path.GetFileName(directoryFullPath); \\ Images
【讨论】:
看看这个答案; C# How do I extract each folder name from a path? 然后只查找数组中的最后一个元素。
【讨论】:
下面的方法会提取所有的目录名和文件名
Dim path As String = "C:\My Documents\Images\Image1.png"
Dim list As String() = path.Split("\")
Console.WriteLine(list.ElementAt(list.Count - 2))
【讨论】: