我有这个代码:
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
我该如何解决?