在u#中将uri转换为字符串

时间:2013-04-24 09:27:10

标签: c# uri

我有这段代码:

   public static string FindRelativePath(string basePatrh, string targetPath)
    {
        Func<FileSystemInfo, string> getFullName = delegate(FileSystemInfo path)
            {
                string fullName = path.FullName;

                if (path is DirectoryInfo)
                {
                    if (fullName[fullName.Length - 1] != Path.DirectorySeparatorChar)
                    {
                        fullName += Path.DirectorySeparatorChar;
                    }
                }

                return fullName;
            };

        string basePatrhFullName = getFullName(new DirectoryInfo(basePatrh));
        string targetPathFullName = getFullName(new DirectoryInfo(targetPath));

        Uri basePatrhUri = new Uri(basePatrhFullName);
        Uri targetPathUri = new Uri(targetPathFullName);
        Uri relativeUri = basePatrhUri.MakeRelativeUri(targetPathUri);

        return relativeUri.ToString().Replace('/', '\\');
    }

此代码将路径转换为与另一个路径相比的相对路径。例如:

   FindRelativePath("c:\test","C;\test\dir1\dir2")

将返回
     dir1 \ dir2

代码运行良好,但如果路径中有空格,例如:

  FindRelativePath("c:\test","C;\test\dir1\dir 2")

它返回错误的字符串:

dir1\dir%202

我该如何解决?

4 个答案:

答案 0 :(得分:1)

您可以使用Uri.UnescapeDataString的反向函数Uri.EscapeDataString

答案 1 :(得分:0)

返回的字符串没有错误%20表示dir 2

之间的空格

答案 2 :(得分:0)

public static string FindRelativePath(string basePath, string targetPath)
{
           return Uri.UnescapeDataString(
                basePath.MakeRelativeUri(targetPath)
                    .ToString()
                    .Replace('/', Path.DirectorySeparatorChar)
                );
}

答案 3 :(得分:0)

“%20”是US-ASCII空格字符的转义编码 所以你必须像Uri.UnescapeDataString

那样对它进行Unescape