[英]Extracting folder names from path
I have a path like this 我有这样一条路
Path = C:\Users\cyberbemon\Documents\Development\Image tool\sources\AL001\2014-05-17\ImageTool\output.xml
I want to extract the folder names 2014-05-17
and AL001
They will later be used as a filename for eg: 140517-AL001.xml
. 我想提取文件夹名称
2014-05-17
和AL001
它们稍后将用作文件名,例如: 140517-AL001.xml
。
The problem is the paths are dynamic, so instead of 2014-05-17
and AL001
I could have something different like 2012-05-17
and AL401
. 问题是路径是动态的,所以不是
2014-05-17
和AL001
我能有这样的事情不同2012-05-17
和AL401
。 The one thing that remains the same is ImageTool\\output.xml
保持不变的一件事是
ImageTool\\output.xml
So what's the C# equivalent of GetParentof(GetParentof(\\ImageTool\\output.xml))
那么C#相当于
GetParentof(GetParentof(\\ImageTool\\output.xml))
When looking around I came across this New DirectoryInfo(Path).Name
This for me returns ImageTool and that's no use to me. 环顾四周时,我遇到了这个
New DirectoryInfo(Path).Name
对我来说,这返回了ImageTool,对我来说这没有用。
If you can guarantee that there are always 3 directory levels then 如果可以保证始终有3个目录级别,则
string p = @"C:\Users\cyberbemon\Documents\Development\Image tool\sources\AL001\2014-05-17\ImageTool\output.xml";
DirectoryInfo di = new DirectoryInfo(p);
string p1 = di.Parent.Parent.Name;
string p2 = di.Parent.Parent.Parent.Name;
The Parent property of a DirectoryInfo class is another DirectoryInfo, so it just a matter to place the appropriate number of recursive call to Parent DirectoryInfo类的Parent属性是另一个DirectoryInfo,因此只需要对Parent进行适当数量的递归调用即可
I should note that the DirectoryInfo
class works also if you pass a file at its constructor. 我应该注意,如果在其构造函数中传递文件,则
DirectoryInfo
类也将起作用。 If you want to stick to the exact nature of the string then you could use the FileInfo class and recover the parent DirectoryInfo using: 如果要坚持字符串的确切性质,则可以使用FileInfo类并使用以下方法恢复父DirectoryInfo:
FileInfo fi = new FileInfo(p);
string p1 = fi.Directory.Parent.Name;
您也可以在目录分隔符上拆分字符串,然后从数组的末尾导航到所需的点。
string[] pathParts = path.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries);
Splitting the string (not as elegant as using IO functions though): 分割字符串(虽然不如使用IO函数那样优雅):
string Path = @"C:\Users\cyberbemon\Documents\Development\Image tool\sources\AL001\2014-05-17\ImageTool\output.xml";
string[] components = Path.Split('\\');
string p1 = components[components.Length - 2];
string p2 = components[components.Length - 3];
You can use System.IO.Path.GetDirectoryName(path)
to get directory from a file/directory. 您可以使用
System.IO.Path.GetDirectoryName(path)
从文件/目录获取目录。 In your case it would be 在你的情况下
Path.GetFileName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(path))))
But it would be more elegant to create a recursive method that take a path and a level in parameters and returns the Directory name. 但是,创建一个采用参数的路径和级别并返回目录名称的递归方法会更加优雅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.