Quantcast
Channel: How to get relative path from absolute path - Stack Overflow
Viewing all articles
Browse latest Browse all 25

Answer by Dave for How to get relative path from absolute path

$
0
0

.NET Core 2.0 has Path.GetRelativePath, else, use this.

/// <summary>/// Creates a relative path from one file or folder to another./// </summary>/// <param name="fromPath">Contains the directory that defines the start of the relative path.</param>/// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param>/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>/// <exception cref="ArgumentNullException"></exception>/// <exception cref="UriFormatException"></exception>/// <exception cref="InvalidOperationException"></exception>public static String MakeRelativePath(String fromPath, String toPath){    if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");    if (String.IsNullOrEmpty(toPath))   throw new ArgumentNullException("toPath");    Uri fromUri = new Uri(fromPath);    Uri toUri = new Uri(toPath);    if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.    Uri relativeUri = fromUri.MakeRelativeUri(toUri);    String relativePath = Uri.UnescapeDataString(relativeUri.ToString());    if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))    {        relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);    }    return relativePath;}

Viewing all articles
Browse latest Browse all 25

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>