删除字符串末尾字符之间的部分字符串

Remove part of a string between characters at the end of the string

我有一个普通字符串,其中包含用户设置的目录。我的目标是添加像 cd 这样的功能 .. 又名“返回目录”我该怎么做?这是字符串内容的示例:c:/test/example/

我想把字符串改成c:/test/

我想删除最后一个子目录。

正如我之前所说,我不能只从字符串中删除“example/”。由用户定义,长度可以变化。

您可以使用 System.IO.Directory.GetParent:

DirectoryInfo parentDir = Directory.GetParent("c:/test/example/");
string result = parentDir.Parent.FullName;

我想你需要处理最后没有 /\ 的情况:

string path = "c:/test/example";
path = path.EndsWith(Path.DirectorySeparatorChar) ? path : path + Path.DirectorySeparatorChar;

您可以在指定文件夹的路径上调用 Path.GetDirectoryName(它不仅用于文件)

结尾的斜杠可能需要先剪掉;你可能会更好地工作 with/ensuring 你只有 以目录分隔符结尾的路径,并使用 Path.Combine 构建路径

这是另一种删除任何路径的最后一个目录的方法,使用 Substring()LastIndexOf(),例如:

var path = "c:/test/example/dir/anotherdir/deepdir";

path = path.Substring(0, path.Trim('/').LastIndexOf('/'));

输出:

c:/test/example/dir/anotherdir
        int position = 0;
        string dir = "c:/test/example/";

        for (int i = dir.Length - 1; i >= 0; i--)
        {
            if (dir.Substring(i - 1, 1) == "/")
            {
                position = i;
                break;
            }
        }

        Console.WriteLine(dir.Substring(0, position));