[editedit] 好的,经过一番思考,我确实想出了一个替代方案,但它可能并不适合所有人:
void Main()
{
var path1 = @"C:\Program Files\Internet Explorer\";
var path2 = @"C:\temp\";
var sb = new StringBuilder(1000);
PathRelativePathTo(sb, path1, 0, path2, 0);
sb.ToString().Dump();
}
/*
BOOL PathRelativePathTo(
_Out_ LPTSTR pszPath,
_In_ LPCTSTR pszFrom,
_In_ DWORD dwAttrFrom,
_In_ LPCTSTR pszTo,
_In_ DWORD dwAttrTo
);
*/
[DllImport("Shlwapi.dll")]
[return:MarshalAs(UnmanagedType.Bool)]
public static extern bool PathRelativePathTo(
[Out] StringBuilder result,
[In] string pathFrom,
[In] int dwAttrFrom,
[In] string pathTo,
[In] int dwAttrTo);
哦,刚刚有了一个想法——这是否(或多或少)满足了您的需求?
public string PathDiff(string path1, string path2)
{
var replace1 = path1.Replace(path2, string.Empty);
var replace2 = path2.Replace(path1, string.Empty);
return Path.IsPathRooted(replace1) ? replace2 : replace1;
}
或者可能更好:
public string PathDiff(string path1, string path2)
{
return path1.Length > path2.Length ?
path1.Replace(path2, string.Empty) :
path2.Replace(path1, string.Empty);
}
(编辑:derp,过早点击提交):
不幸的是,没有内置的相对路径助手,但你基本上已经有了你所拥有的,就像这样:
var path1 = @"C:\dev\src\release\Frontend\";
var path2 = @"C:\dev\src\";
var path1Uri = new Uri(path1);
var path2Uri = new Uri(path2);
var from1to2 = path1Uri.MakeRelativeUri(path2Uri).OriginalString;
var from2to1 = path2Uri.MakeRelativeUri(path1Uri).OriginalString;
Console.WriteLine("To go from {0} to {1}, you need to {2}", path1, path2, from1to2);
Console.WriteLine("To go from {0} to {1}, you need to {2}", path2, path1, from2to1);
输出:
To go from C:\dev\src\release\Frontend\ to C:\dev\src\, you need to ../../
To go from C:\dev\src\ to C:\dev\src\release\Frontend\, you need to release/Frontend/
现在,对于斜线差异“\”与“/”,如果将最终结果包装在 中Path.GetFullPath
,它将自动解决差异:
Console.WriteLine(Path.GetFullPath(Path.Combine(path1, from1to2)));
Console.WriteLine(Path.GetFullPath(Path.Combine(path2, from2to1)));
输出:
C:\dev\src\
C:\dev\src\release\Frontend\