如何解决' ..'在C#中的相对路径

时间:2015-01-19 15:24:34

标签: c# path

假设我将以下相对路径作为字符串:

"foo/./my/../bar/file.txt"

是否有快速解决点的方法(如“..”和“。”),以便结果如下:

"foo/bar/file.txt"

我不能使用Uri,因为它不是绝对路径,我也不能使用Path.GetFullPath,因为这将添加正在执行的应用程序的路径,以便我最终得到:

 "C:\myAppPath\foo\bar\file.txt"

(也改变了“/” - >“\”,但我并不特别介意)

2 个答案:

答案 0 :(得分:3)

只是一个黑客,

string path = @"foo/./my/../bar/file.txt";
string newPath = Path.GetFullPath(path).Replace(Environment.CurrentDirectory, "");

您可以使用Path.GetFullPathEnvironment.CurrentDirectory一起返回路径,使用String.Replace已解析路径中删除当前目录。

您最终会得到newPath = \foo\bar\file.txt

答案 1 :(得分:1)

你总是可以这样做。这样做了吗?

        string test = "foo/./my/../bar/file.txt";

        bool temp = false;
        string result = "";
        foreach (var str in test.Split('/'))
        {
            if (str.Contains(".") & str.Count(f => f=='.') == str.Length)
            {
                if (temp == false)
                    temp = true;
                else
                    temp = false;
            }
            else
            {
                if (!temp)
                {
                    result += str + "/";

                }
            }
        }
        result = result.Substring(0, result.Length - 1);//is there a better way to do this?
        //foo/bar/file.txt
相关问题