2

我有这个代码:

   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

4 回答 4

1

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

于 2013-04-24T09:33:01.717 回答
0

"%20" 是 US-ASCII 空格字符的转义编码所以你必须像 Uri.UnescapeDataString 一样取消转义它

于 2013-04-24T09:59:44.080 回答
0

返回的字符串没有错 %20 表示之间的空格dir 2

于 2013-04-24T09:30:24.927 回答
0
public static string FindRelativePath(string basePath, string targetPath)
{
           return Uri.UnescapeDataString(
                basePath.MakeRelativeUri(targetPath)
                    .ToString()
                    .Replace('/', Path.DirectorySeparatorChar)
                );
}
于 2013-04-24T09:43:18.010 回答