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

5
例如,
string path = @"C:\User\Desktop\Drop\images\";

我需要获取@"C:\User\Desktop\Drop\路径。

有没有简单的方法可以做到这一点?

7个回答

11

您可以使用 PathDirectory 类:

DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName; 

请注意,如果路径不以目录分隔符字符\结尾,则会得到不同的结果。那么images将被视为文件名而不是目录。

还可以使用Path.GetDirectoryName的后续调用。

string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));

这种行为在此处有记录:

因为返回的路径不包括DirectorySeparatorChar或AltDirectorySeparatorChar,将返回的路径再次传递到GetDirectoryName方法中将导致每个后续调用结果字符串缩短一个文件夹级别。例如,将路径"C:\Directory\SubDirectory\test.txt"传入GetDirectoryName方法将返回"C:\Directory\SubDirectory"。将该字符串"C:\Directory\SubDirectory"传入GetDirectoryName将导致返回"C:\Directory"。


1
+1 只有使用 Directory.GetParent 的解决方案是更安全、更好的方法,而不是字符串操作。 - Habib
1
在编程中,例如这个 Path.GetDirectoryName(Path.GetDirectoryName(path)),将会返回所需的结果,具体取决于路径中是否包含尾部斜杠。如果 GetDirectoryName 返回当前级别或父级,则会得到不同的结果。 - drk
只要人们意识到GetDirectoryName的不同结果,这就可以回答问题了 - 获得了赞同。对于更复杂的情况,我添加了自己的答案,并进行了尾部斜杠检查。 - drk

1
翻译:简短回答 :)
path = Directory.GetParent(Directory.GetParent(path)).ToString();

1
这将返回 "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));

1
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);

正如我所评论的,GetDirectoryName是自动折叠的,它返回不带尾部斜杠的路径 - 允许获取下一个目录。如果使用Directory.GetParent来关闭,则也是有效的。


0

0
using System;

namespace Programs
{
    public class Program
    {      
        public static void Main(string[] args)
        {
            string inputText = @"C:\User\Desktop\Drop\images\";
            Console.WriteLine(inputText.Substring(0, 21));
        }
    }
}

输出:

C:\User\Desktop\Drop\


不过在这种情况下,这不是一个解决方案吗?我们没有包括其他信息。 - Soner Gönül
一个非常特定的情况下 --- 但是编写好的软件难道不一直都是关于一次只解决一个问题吗? - Yuck
当然。你是对的,但是当我看到这个问题时,我的答案看起来很好。当然,这个问题不好,但我的答案是对提问者有帮助的解决方案。但是当然,我再次说,你是对的。 - Soner Gönül

0

可能有一些使用File或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...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接