PtiTom

GetRelativePath

Feb 9th, 2015
211
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static string BuildRelativePath(string referencePath, string destinationPath)
  2. {
  3.     // Check both are absolute :
  4.     DirectoryInfo destination = new DirectoryInfo(destinationPath);
  5.     string destinationAbsolutePath = destination.FullName;
  6.  
  7.     string referenceAbsolutePath;
  8.     if (referencePath.EndsWith(@"\") || referencePath.LastIndexOf('.') <= referencePath.LastIndexOf('\\'))
  9.     {   // It's a folder.
  10.         referenceAbsolutePath = new DirectoryInfo(referencePath).FullName;
  11.     }
  12.     else
  13.     {   // It's a file.
  14.         referenceAbsolutePath = new FileInfo(referencePath).FullName;
  15.     }
  16.  
  17.     // Attention aux UNC !
  18.     string[] splittedTargetPath = destinationAbsolutePath.Split(@"\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  19.     string[] splittedSourcePath = referenceAbsolutePath.Split(@"\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
  20.  
  21.     if (splittedSourcePath[0] != splittedTargetPath[0])
  22.     {
  23.         // Aucune racine commune : On retourne le chemin absolu.
  24.         return destinationAbsolutePath;
  25.     }
  26.  
  27.     int deeperSimilarLevel = 0;
  28.  
  29.     while (splittedSourcePath[deeperSimilarLevel] == splittedTargetPath[deeperSimilarLevel])
  30.     {
  31.         deeperSimilarLevel++;
  32.         if (deeperSimilarLevel >= splittedSourcePath.Length || deeperSimilarLevel >= splittedTargetPath.Length)
  33.         {
  34.             break;
  35.         }
  36.     }
  37.  
  38.     StringBuilder relativePath = new StringBuilder();
  39.     for (int sourceRewind = deeperSimilarLevel; sourceRewind < splittedSourcePath.Length; sourceRewind++)
  40.     {
  41.         relativePath.Append(@"..\");
  42.     }
  43.  
  44.     if (relativePath.Length == 0)
  45.     {
  46.         relativePath.Append(@".\");
  47.     }
  48.  
  49.     for (int targetForward = deeperSimilarLevel; targetForward < splittedTargetPath.Length - 1; targetForward++)
  50.     {
  51.         relativePath.AppendFormat(@"{0}\", splittedTargetPath[targetForward]);
  52.     }
  53.  
  54.     if (deeperSimilarLevel < splittedTargetPath.Length)
  55.     {
  56.         relativePath.AppendFormat(@"{0}", splittedTargetPath[splittedTargetPath.Length - 1]);
  57.     }
  58.  
  59.     return relativePath.ToString();
  60. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×