Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static string BuildRelativePath(string referencePath, string destinationPath)
- {
- // Check both are absolute :
- DirectoryInfo destination = new DirectoryInfo(destinationPath);
- string destinationAbsolutePath = destination.FullName;
- string referenceAbsolutePath;
- if (referencePath.EndsWith(@"\") || referencePath.LastIndexOf('.') <= referencePath.LastIndexOf('\\'))
- { // It's a folder.
- referenceAbsolutePath = new DirectoryInfo(referencePath).FullName;
- }
- else
- { // It's a file.
- referenceAbsolutePath = new FileInfo(referencePath).FullName;
- }
- // Attention aux UNC !
- string[] splittedTargetPath = destinationAbsolutePath.Split(@"\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
- string[] splittedSourcePath = referenceAbsolutePath.Split(@"\".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
- if (splittedSourcePath[0] != splittedTargetPath[0])
- {
- // Aucune racine commune : On retourne le chemin absolu.
- return destinationAbsolutePath;
- }
- int deeperSimilarLevel = 0;
- while (splittedSourcePath[deeperSimilarLevel] == splittedTargetPath[deeperSimilarLevel])
- {
- deeperSimilarLevel++;
- if (deeperSimilarLevel >= splittedSourcePath.Length || deeperSimilarLevel >= splittedTargetPath.Length)
- {
- break;
- }
- }
- StringBuilder relativePath = new StringBuilder();
- for (int sourceRewind = deeperSimilarLevel; sourceRewind < splittedSourcePath.Length; sourceRewind++)
- {
- relativePath.Append(@"..\");
- }
- if (relativePath.Length == 0)
- {
- relativePath.Append(@".\");
- }
- for (int targetForward = deeperSimilarLevel; targetForward < splittedTargetPath.Length - 1; targetForward++)
- {
- relativePath.AppendFormat(@"{0}\", splittedTargetPath[targetForward]);
- }
- if (deeperSimilarLevel < splittedTargetPath.Length)
- {
- relativePath.AppendFormat(@"{0}", splittedTargetPath[splittedTargetPath.Length - 1]);
- }
- return relativePath.ToString();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement