, , System.Uri PathDifference. Reflector . DOS URI, .
static string PathDifference(string path1, string path2)
{
int c = 0;
int d = -1;
while (c < path1.Length && c < path2.Length)
{
if (char.ToLowerInvariant(path1[c]) != char.ToLowerInvariant(path2[c]))
{
break;
}
if (path1[c] == '\\')
{
d = c;
}
c++;
}
if (c == 0)
{
return path2;
}
if (c == path1.Length && c == path2.Length)
{
return string.Empty;
}
System.Text.StringBuilder builder = new System.Text.StringBuilder();
while (c < path1.Length)
{
if (path1[c] == '\\')
{
builder.Append(@"..\");
}
c++;
}
if (builder.Length == 0 && path2.Length - 1 == d)
{
return @".\";
}
return builder.ToString() + path2.Substring(d + 1);
}
, -, , , . , .
... , .
Path1 Path2 Output
C:\test\path1\path2\ C:\test\ ..\..\
C:\test\path1\file C:\test\ ..\
C:\test\path1\path2\ C:\ ..\..\..\
C:\test\path1\path2\ D:\ D:\
C:\test\path1\path2\ C:\test\path1\pathA ..\pathA
C:\test\ C:\test\
C:\test\ C:\test\file file
C:\test\file C:\test\ .\
C:\test\path