Du bist hier: Snippet-Verzeichnis » Microsoft .NET (154)
Sprache:

Convert Absolute To Relative Path with C#

Sprache: English
Programmiersprache: C#
Veröffentlicht von: Thomas
Letzte Änderung: 07.06.2006
Aufrufe: 3937

Beschreibung

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 }

Ein Kommentar

1

newPath += "/";

should be

newPath += Path.DirectorySeparatorChar;

Montag, 1. Januar 0001 00:00:00 von Don

Dieses Snippet kommentieren

Name *  

E-Mail (wird nicht angezeigt) *    

Website  

Kommentar *  

Sicherheitscode Sicherheitscode *    

RSS