C# 在c中将uri转换为字符串#
我有以下代码:C# 在c中将uri转换为字符串#,c#,uri,C#,Uri,我有以下代码: public static string FindRelativePath(string basePatrh, string targetPath) { Func<FileSystemInfo, string> getFullName = delegate(FileSystemInfo path) { string fullName = path.FullName;
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('/', '\\');
}
将返回dir1\dir2 代码运行良好,但如果路径中有空间,例如:
FindRelativePath("c:\test","C;\test\dir1\dir 2")
它返回错误的字符串:
dir1\dir%202
我怎样才能修好它 返回的字符串没有错误%20表示可以使用的
dir
2之间的空格。%20”是US-ASCII空格字符的转义编码
因此,您必须像Uri.UnescapeDataString一样对其进行Unescape
dir1\dir%202
public static string FindRelativePath(string basePath, string targetPath)
{
return Uri.UnescapeDataString(
basePath.MakeRelativeUri(targetPath)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
}