Introduction
In a project, it is often necessary to convert an absolute path to a relative path to increase the flexibility of the program-related configuration (not because our program does not work properly because of the overall move).
Problem Solving Methods
Write your own code to resolve:
private string RelativePath (String Absolutepath, String relativeto) {string[] absolutedirectories = a
Bsolutepath.split (' \ \ ');
string[] relativedirectories = relativeto.split (' \ \ '); Get the shortest of the two paths int length = Absolutedirectories.length < relativedirectories.length?
AbsoluteDirectories.Length:relativeDirectories.Length;
Use to determine where in the loop we exited int lastcommonroot =-1;
int index; Find common root for (index = 0; index < length; index++) if (Absolutedirectories[index)
= = Relativedirectories[index]) lastcommonroot = index;
else break; If we didn ' t find a common prefix then throw if (Lastcommonroot = 1) throw new Argumentexc
Eption ("Paths do not have a common base"); Build up the relative pAth StringBuilder relativepath = new StringBuilder ();
Add on the.. for (index = lastcommonroot + 1; index < absolutedirectories.length; index++) if (absolutedirectories[i Ndex]. Length > 0) relativepath.append ("..
\\");
ADD on the folders for (index = lastcommonroot + 1; index < relativedirectories.length-1; index++)
Relativepath.append (Relativedirectories[index] + "\");
Relativepath.append (Relativedirectories[relativedirectories.length-1]);
return relativepath.tostring (); }
Resolved by URI classes in C #:
System.Uri uri1 = new Uri (@ "C:\filename.txt");
System.Uri uri2 = new Uri (@ "C:\mydirectory\anotherdirectory\");
Uri relativeuri = Uri2. Makerelativeuri (URI1);
Console.WriteLine (Relativeuri.tostring ());
Reference Documents
Http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri (v=vs.110). aspx