c# - 如何在 C# 中获取路径字符串中的倒数第二个目录

标签 c# string path directory

例如,

string path = @"C:\User\Desktop\Drop\images\";

我只需要获取 @"C:\User\Desktop\Drop\

有什么简单的方法可以做到这一点吗?

最佳答案

您可以使用 PathDirectory 类:

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/

相关文章:

c# - 调整 Datagridview 上的行标题属性

c# - 如何在 Word 文件中查找数学方程式,如果找到则使用 vsto c# 突出显示它

c# - Android Unity3d 限制 streamingAssetsPath 只有启动方法(更新设备/版本或设置?)

php - 如何在另一个字符串中插入一个字符串?

java - 比较字符串避免 NullPointerException

string - VBA将多个变量连接成字符串

java - netbeans、cmd 和 .bat 或 .cmd 中的路径差异

node.js - 模块内的相对文件系统写入路径

javascript - 数据操作 : How can I append path from my data array?

c# - 如何在 C# 中构建混合架构框架?