[英]get directory from full path
If i have:如果我有:
C:\temp\foo\bar\ C:\temp\foo\bar\
( NOTE: bar is a directory) (注意: bar 是一个目录)
how can i parse out:我该如何解析:
bar酒吧
I figured it out.我想到了。
DirectoryInfo info = new DirectoryInfo(sourceDirectory_);
string currentDirectoryName = info.Name;
Try尝试
System.IO.Path.GetFileName("C:\\temp\\foo\\bar");
Just use:只需使用:
string dirname = new DirectoryInfo(@"C:\temp\foo\bar\").Name;
According to MSDN this returns the name of the directory, not the full path.根据 MSDN,这将返回目录的名称,而不是完整路径。
Link to MSDN Library 链接到 MSDN 库
Hope this helps.........希望这可以帮助.........
It looks like a bunch of people have withdrawn their answers, which is possibly a shame.看起来一堆人撤回了他们的答案,这可能是一种耻辱。
This one's got to be worth stating, only for the "teach a man to fish" quality of it - it's short, elegant and made of two separate things that, once learned, can be re-applied to other problems.值得一提的是,它具有“教人钓鱼”的品质——它简短、优雅,由两个独立的东西组成,一旦学会,就可以重新应用于其他问题。
string lastPiece = wholePath.Split('\\').Last();
Last
will throw if the list is empty.如果列表为空,
Last
将抛出。
The simplest way to do this without creating a new DirectoryInfo instance is to use the Path.GetFileName static method.在不创建新DirectoryInfo实例的情况下执行此操作的最简单方法是使用Path.GetFileName static 方法。 This is located in System.IO.
它位于 System.IO 中。
using System.IO;
string lastFolderName = Path.GetFileName(@"C:\Folder1\Folder2");
The variable would be set to "Folder2".该变量将设置为“Folder2”。
This is quite a bit more efficient that creating a new instance of the DirectoryInfo class!这比创建 DirectoryInfo 类的新实例要高效得多!
I can think of 4 ways instantly我可以立即想到 4 种方法
string dirname = new DirectoryInfo(path).Name;
Console.WriteLine(dirname);
In Unix this is known as the basename, a quick google came up with this link for a C# version .在 Unix 中,这被称为基本名称,一个快速的 google 想出了这个C# 版本的链接。 I'm sure there are others...
我确定还有其他人...
if the answers above do not satisfy your needs, why not just substring the string from the last.如果上面的答案不能满足您的需求,为什么不只是 substring 从最后一个字符串。
string dirName = originalDirName.Substring(originalDirName.LastIndexOf("\\") + 1);
sure, you should do some checking if the originalDirName does not end on a \ and if the originalDirName is longer than zero and actually contains \ characters.当然,您应该检查 originalDirName 是否不以 \ 结尾,以及 originalDirName 是否长于零并且实际上包含 \ 字符。
Try this尝试这个
string DirName = System.IO.Directory.GetParent(@"C:\temp\foo\bar\").Name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.