andrew4582

GetRelativePath

Apr 21st, 2013
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. /// <summary>
  2.         /// Returns a relative path string from a full path.
  3.         /// </summary>
  4.         /// <param name="FullPath">The path to convert. Can be either a file or a directory</param>
  5.         /// <param name="BasePath">The base path to truncate to and replace</param>
  6.         /// <returns>
  7.         /// Lower case string of the relative path. If path is a directory it's returned without a backslash at the end.
  8.         ///
  9.         /// Examples of returned values:
  10.         ///  .\test.txt, ..\test.txt, ..\..\..\test.txt, ., ..
  11.         /// </returns>
  12.         public static string GetRelativePath(string FullPath, string BasePath)
  13.         {
  14.             // *** Start by normalizing paths
  15.             FullPath = FullPath.ToLower();
  16.             BasePath = BasePath.ToLower();
  17.  
  18.             if (BasePath.EndsWith("\\"))
  19.                 BasePath = BasePath.Substring(0, BasePath.Length - 1);
  20.             if (FullPath.EndsWith("\\"))
  21.                 FullPath = FullPath.Substring(0, FullPath.Length - 1);
  22.  
  23.             // *** First check for full path
  24.             if ((FullPath + "\\").IndexOf(BasePath + "\\") > -1)
  25.                 return FullPath.Replace(BasePath, ".");
  26.  
  27.             // *** Now parse backwards
  28.             string BackDirs = "";
  29.             string PartialPath = BasePath;
  30.             int Index = PartialPath.LastIndexOf("\\");
  31.             while (Index > 0)
  32.             {
  33.                 // *** Strip path step string to last backslash
  34.                 PartialPath = PartialPath.Substring(0, Index);
  35.  
  36.                 // *** Add another step backwards to our pass replacement
  37.                 BackDirs = BackDirs + "..\\";
  38.  
  39.                 // *** Check for a matching path
  40.                 if (FullPath.IndexOf(PartialPath) > -1)
  41.                 {
  42.                     if (FullPath == PartialPath)
  43.                         // *** We're dealing with a full Directory match and need to replace it all
  44.                         return FullPath.Replace(PartialPath, BackDirs.Substring(0, BackDirs.Length - 1));
  45.                     else
  46.                         // *** We're dealing with a file or a start path
  47.                         return FullPath.Replace(PartialPath + (FullPath == PartialPath ? "" : "\\"), BackDirs);
  48.                 }
  49.                 Index = PartialPath.LastIndexOf("\\", PartialPath.Length - 1);
  50.             }
  51.  
  52.             return FullPath;
  53.         }
Advertisement
Add Comment
Please, Sign In to add comment