例如,
string path = @"C:\User\Desktop\Drop\images\";
我只需要获取 @"C:\User\Desktop\Drop\
有什么简单的方法可以做到这一点吗?
最佳答案
您可以使用 Path
和 Directory
类:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
请注意,如果路径不以目录分隔符字符 \
结尾,您将得到不同的结果。然后 images
将被理解为文件名而不是目录。
您还可以使用 Path.GetDirectoryName
的后续调用
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
此行为已记录 here :
Because the returned path does not include the DirectorySeparatorChar or AltDirectorySeparatorChar, passing the returned path back into the GetDirectoryName method will result in the truncation of one folder level per subsequent call on the result string. For example, passing the path "C:\Directory\SubDirectory\test.txt" into the GetDirectoryName method will return "C:\Directory\SubDirectory". Passing that string, "C:\Directory\SubDirectory", into GetDirectoryName will result in "C:\Directory".
关于c# - 如何在 C# 中获取路径字符串中的倒数第二个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933223/