You're here: Snippet Directory » Microsoft .NET (152)
Language:

Convert Absolute To Relative Path with C#

Language: English
Programming Language: C#
Published by: Thomas
Last Update: 6/7/2006
Views: 2866

Description

Converts a absolute to a relative path

Code

1 private static string EvaluateRelativePath(string mainDirPath, string absoluteFilePath) 2 { 3 4 string[] firstPathParts = mainDirPath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); 5 string[] secondPathParts = absoluteFilePath.Trim(Path.DirectorySeparatorChar).Split(Path.DirectorySeparatorChar); 6 7 int sameCounter = 0; 8 for (int i = 0; i < Math.Min(firstPathParts.Length, secondPathParts.Length); i++) 9 { 10 if (!firstPathParts[i].ToLower().Equals(secondPathParts[i].ToLower())) 11 { 12 break; 13 } 14 sameCounter++; 15 } 16 17 if (sameCounter == 0) 18 { 19 return absoluteFilePath; 20 } 21 22 string newPath = String.Empty; 23 for (int i = sameCounter; i < firstPathParts.Length; i++) 24 { 25 if (i > sameCounter) 26 { 27 newPath += Path.DirectorySeparatorChar; 28 } 29 newPath += ".."; 30 } 31 if (newPath.Length == 0) 32 { 33 newPath = "."; 34 } 35 for (int i = sameCounter; i < secondPathParts.Length; i++) 36 { 37 newPath += "/"; 38 newPath += secondPathParts[i]; 39 } 40 return newPath; 41 }

One comment

1

newPath += "/";

should be

newPath += Path.DirectorySeparatorChar;

Monday, January 01, 0001 12:00:00 AM from Don

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS