C# 如何在C中获取路径字符串中倒数第二个目录#
比如说,C# 如何在C中获取路径字符串中倒数第二个目录#,c#,string,path,directory,C#,String,Path,Directory,比如说, string path = @"C:\User\Desktop\Drop\images\"; 我只需要获得@“C:\User\Desktop\Drop\ 有什么简单的方法可以做到这一点吗?这将返回“C:\User\Desktop\Drop\”例如,除了最后一个子目录之外的所有内容 string path = @"C:\User\Desktop\Drop\images"; string sub = path.Substring(0, path.LastIndexOf(@"\") + 1
string path = @"C:\User\Desktop\Drop\images\";
我只需要获得@“C:\User\Desktop\Drop\
有什么简单的方法可以做到这一点吗?这将返回“C:\User\Desktop\Drop\”例如,除了最后一个子目录之外的所有内容
string path = @"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(@"\") + 1);
如果有尾随斜杠,另一种解决方案是:
string path = @"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(@"\", splitedPath.Take(splitedPath.Length - 2));
页面底部的示例可能会有所帮助: 输出: C:\User\Desktop\Drop\
您可以使用
路径
和目录
类:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
请注意,如果路径没有以目录分隔符char结尾,则会得到不同的结果。\
。然后,图像将被理解为文件名,而不是目录
您还可以使用Path.GetDirectoryName
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
这种行为被记录在案:
因为返回的路径不包括DirectorySpeparatorChar
或AltDirectorySpeparatorChar,将返回的路径传递回
GetDirectoryName方法将导致截断一个文件夹
每次对结果字符串的后续调用的级别。例如,传递
将路径“C:\Directory\SubDirectory\test.txt”插入
GetDirectoryName方法将返回“C:\Directory\SubDirectory”。
将字符串“C:\Directory\SubDirectory”传递到
GetDirectoryName将生成“C:\Directory”
使用File或Path类可能有一些简单的方法来实现这一点,但您也可以通过这样做来解决(注意:未测试):
正如我所评论的,GetDirectoryName是自折叠的,它返回的路径不带斜杠-允许获取下一个目录。使用directory.GetParent作为clouse也是有效的。简短回答:)
不,但在这种情况下,这不是一个解决方案吗?我们没有其他信息包括这一点。在一个非常具体的情况下——但编写好的软件什么时候会一次硬编码一个问题?当然。你是对的,但当我看这个问题时,我的答案看起来不错。当然这个问题不好,但我的答案是解决方案对于询问方来说,这是一种更安全、更好的方法。但是,当然我再说一遍,你是对的。+1是使用Directory.GetParent
的唯一解决方案,它比字符串操作更安全、更好。在给定的示例中,这个Path.GetDirectoryName(Path.GetDirectoryName(Path))将返回所需的结果,取决于尾随斜杠的位置,只要ppl知道与GetDirectoryName不同的结果,GetDirectoryName将返回当前或父级。这应该包括问题-向上投票。对于更复杂的场景,我添加了我自己的答案和尾随斜杠检查
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
string fullPath = "C:\User\Desktop\Drop\images\";
string[] allDirs = fullPath.split(System.IO.Path.PathSeparator);
string lastDir = allDirs[(allDirs.length - 1)];
string secondToLastDir= allDirs[(allDirs.length - 2)];
// etc...
var parent = "";
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
parent = Path.GetDirectoryName(path);
path = Directory.GetParent(Directory.GetParent(path)).ToString();