I wish I could credit the person who wrote this first, but I've since lost the link.
From my utilities collection:
/// <summary>
/// Generates a Relative Path for targetPath, from basePath
/// </summary>
/// <param name="basePath">The Directory to start from.</param>
/// <param name="targetPath">Full Path to file or folder that is to be made relative</param>
/// <returns>The relative location of targetPath, from basePath</returns>
/// <remarks>Tested in Util.Tests.IO.PathUtilsTests</remarks>
public static string MakeRelativePath(string basePath, string targetPath)
{
if (basePath == targetPath)
return "";
if (!basePath.EndsWith(Path.DirectorySeparatorChar.ToString()))
basePath += Path.DirectorySeparatorChar;
if (String.IsNullOrEmpty(basePath)) throw new ArgumentNullException("basePath");
if (String.IsNullOrEmpty(targetPath)) throw new ArgumentNullException("targetPath");
var fromUri = new Uri(basePath);
var toUri = new Uri(targetPath);
if (fromUri.Scheme != toUri.Scheme) { return targetPath; } // path can't be made relative.
var relativeUri = fromUri.MakeRelativeUri(toUri);
var relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
Usage:
var output = @"C:\Users\Documents\MyWeb\Slide\Main\slider2.png";
var basePath = @"C:\Users\Documents\MyWeb\";
var rel = MakeRelativePath(basePath, output);