我有這樣的代碼:URI轉換爲字符串在C#中
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
我該如何解決?