public static string GetRelativePath(string fullPath, string basePath = null)
{
Argument.IsNotNullOrWhitespace("fullPath", fullPath);
#if !NETFX_CORE && !PCL
if (string.IsNullOrEmpty(basePath))
{
basePath = Environment.CurrentDirectory;
}
#endif
fullPath = RemoveTrailingSlashes(fullPath.ToLower());
basePath = RemoveTrailingSlashes(basePath.ToLower());
// Check if the base path is really the full path (not just a subpath, for example "C:\MyTes" in "C:\MyTest")
string fullPathWithTrailingBackslash = AppendTrailingSlash(fullPath);
string basePathWithTrailingBackslash = AppendTrailingSlash(basePath);
if (fullPathWithTrailingBackslash.IndexOf(basePathWithTrailingBackslash) > -1)
{
string result = fullPath.Replace(basePath, string.Empty);
if (result.StartsWith("\\"))
{
result = result.Remove(0, 1);
}
return result;
}
string backDirs = string.Empty;
string partialPath = basePath;
int index = partialPath.LastIndexOf("\\");
while (index > 0)
{
partialPath = AppendTrailingSlash(partialPath.Substring(0, index));
backDirs = backDirs + "..\\";
if (fullPathWithTrailingBackslash.IndexOf(partialPath) > -1)
{
partialPath = RemoveTrailingSlashes(partialPath);
fullPath = RemoveTrailingSlashes(fullPath);
if (fullPath == partialPath)
{
// *** 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 ? string.Empty : "\\"), backDirs);
}
}
partialPath = RemoveTrailingSlashes(partialPath);
index = partialPath.LastIndexOf("\\", partialPath.Length - 1);
}
return fullPath;
}