Last active
April 25, 2016 02:44
-
-
Save mattjcowan/ae21ca6d9835c9630b362dd17141f863 to your computer and use it in GitHub Desktop.
Get relative path from one file to another on windows in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See here for the following 2 methods: http://stackoverflow.com/questions/703281/getting-path-relative-to-the-current-working-directory | |
/// <summary> | |
/// Gets the relative path ("..\..\to_file_or_dir") of the current file/dir (to) in relation to another (from) | |
/// </summary> | |
/// <param name="to"></param> | |
/// <param name="from"></param> | |
/// <returns></returns> | |
public static string GetRelativePathFrom(this FileSystemInfo to, FileSystemInfo from) | |
{ | |
return from.GetRelativePathTo(to); | |
} | |
/// <summary> | |
/// Gets the relative path ("..\..\to_file_or_dir") of another file or directory (to) in relation to the current file/dir (from) | |
/// </summary> | |
/// <param name="to"></param> | |
/// <param name="from"></param> | |
/// <returns></returns> | |
public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to) | |
{ | |
Func<FileSystemInfo, string> getPath = fsi => | |
{ | |
var d = fsi as DirectoryInfo; | |
return d == null ? fsi.FullName : d.FullName.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; | |
}; | |
var fromPath = getPath(from); | |
var toPath = getPath(to); | |
var fromUri = new Uri(fromPath); | |
var toUri = new Uri(toPath); | |
var relativeUri = fromUri.MakeRelativeUri(toUri); | |
var relativePath = Uri.UnescapeDataString(relativeUri.ToString()); | |
return relativePath.Replace('/', Path.DirectorySeparatorChar); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment