Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Returns a relative path string from a full path.
- /// </summary>
- /// <param name="FullPath">The path to convert. Can be either a file or a directory</param>
- /// <param name="BasePath">The base path to truncate to and replace</param>
- /// <returns>
- /// Lower case string of the relative path. If path is a directory it's returned without a backslash at the end.
- ///
- /// Examples of returned values:
- /// .\test.txt, ..\test.txt, ..\..\..\test.txt, ., ..
- /// </returns>
- public static string GetRelativePath(string FullPath, string BasePath)
- {
- // *** Start by normalizing paths
- FullPath = FullPath.ToLower();
- BasePath = BasePath.ToLower();
- if (BasePath.EndsWith("\\"))
- BasePath = BasePath.Substring(0, BasePath.Length - 1);
- if (FullPath.EndsWith("\\"))
- FullPath = FullPath.Substring(0, FullPath.Length - 1);
- // *** First check for full path
- if ((FullPath + "\\").IndexOf(BasePath + "\\") > -1)
- return FullPath.Replace(BasePath, ".");
- // *** Now parse backwards
- string BackDirs = "";
- string PartialPath = BasePath;
- int Index = PartialPath.LastIndexOf("\\");
- while (Index > 0)
- {
- // *** Strip path step string to last backslash
- PartialPath = PartialPath.Substring(0, Index);
- // *** Add another step backwards to our pass replacement
- BackDirs = BackDirs + "..\\";
- // *** Check for a matching path
- if (FullPath.IndexOf(PartialPath) > -1)
- {
- if (FullPath == PartialPath)
- // *** We're dealing with a full Directory match and need to replace it all
- return FullPath.Replace(PartialPath, BackDirs.Substring(0, BackDirs.Length - 1));
- else
- // *** We're dealing with a file or a start path
- return FullPath.Replace(PartialPath + (FullPath == PartialPath ? "" : "\\"), BackDirs);
- }
- Index = PartialPath.LastIndexOf("\\", PartialPath.Length - 1);
- }
- return FullPath;
- }
Advertisement
Add Comment
Please, Sign In to add comment