C # convert relative paths to absolute paths, and convert absolute paths to relative paths,
1. absolute path to relative path
It seems that C # has not provided the Implementation, and you need to write it yourself. Here we have selected a Boyou implementation method:
String RelativePath (string absolutePath, string relativeTo) {// from-www.cnphp6.com string [] absoluteDirectories = absolutePath. 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 ArgumentException ("Paths do not have a common base "); // Build up the relative path StringBuilder relativePath = new StringBuilder (); // Add on .. for (index = lastCommonRoot + 1; index <absoluteDirectories. length; index ++) if (absoluteDirectories [index]. 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 ();}RelativePath
Call:
static void Main(string[] args){ var path = RelativePath(@"D:\MyProj\Release", @"D:\MyProj\Log\MyFile.txt"); Console.WriteLine(path);//print ..\Log\MyFile.txt Console.Read();}
2. Convert relative paths to absolute paths
You can directly use. Net's own Path. GetFullPath for conversion.
static void Main(string[] args){ var relativePath = @"..\..\Release"; Console.WriteLine(Path.GetFullPath(relativePath)); Console.Read();}