网站制作开发中,URL的绝对路径和相对路径之间互相转换,是经常需要用到的。以下是在C#.Net下一种实现二者互相转化的方法:
[DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
public static extern bool PathRelativePathTo(
[Out] StringBuilder pszPath,
string pszFrom,
FileAttributes dwAttrFrom,
string pszTo,
FileAttributes dwAttrTo
);
public static string ToRelativePath(string basePath, string absolutePath)
{
StringBuilder path = new StringBuilder(260);
PathRelativePathTo(path, basePath, FileAttributes.Normal,
absolutePath, FileAttributes.Normal);
string r = path.ToString();
if (r.StartsWith(".\"))
{
return r.Substring(2);
}
return r;
}
public static string ToAbsolutePath(string basePath, string relativePath)
{
return new Uri(new Uri(basePath), relativePath).ToString();//如果是文件路径将/替换为
}