There\'s a part in my apps that displays the file path loaded by the user through OpenFileDialog. It\'s taking up too much space to display the whole path, but I don\'t want
If you're sure that your absolute path 2 is always relative to absolute path, just remove the first N characters from path2, where N is the length of path1.
public static string ToRelativePath(string filePath, string refPath)
{
var pathNormalized = Path.GetFullPath(filePath);
var refNormalized = Path.GetFullPath(refPath);
refNormalized = refNormalized.TrimEnd('\\', '/');
if (!pathNormalized.StartsWith(refNormalized))
throw new ArgumentException();
var res = pathNormalized.Substring(refNormalized.Length + 1);
return res;
}
The function that uses URI returned "almost" relative path. It included directory that directly contains the file which relative path I wanted to get.
Some time ago I wrote a simple function that returns relative path of folder or file, and even if it's on another drive, it includes the drive letter as well.
Please take a look:
public static string GetRelativePath(string BasePath, string AbsolutePath)
{
char Separator = Path.DirectorySeparatorChar;
if (string.IsNullOrWhiteSpace(BasePath)) BasePath = Directory.GetCurrentDirectory();
var ReturnPath = "";
var CommonPart = "";
var BasePathFolders = BasePath.Split(Separator);
var AbsolutePathFolders = AbsolutePath.Split(Separator);
var i = 0;
while (i < BasePathFolders.Length & i < AbsolutePathFolders.Length)
{
if (BasePathFolders[i].ToLower() == AbsolutePathFolders[i].ToLower())
{
CommonPart += BasePathFolders[i] + Separator;
}
else
{
break;
}
i += 1;
}
if (CommonPart.Length > 0)
{
var parents = BasePath.Substring(CommonPart.Length - 1).Split(Separator);
foreach (var ParentDir in parents)
{
if (!string.IsNullOrEmpty(ParentDir))
ReturnPath += ".." + Separator;
}
}
ReturnPath += AbsolutePath.Substring(CommonPart.Length);
return ReturnPath;
}
Use:
RelPath = AbsPath.Replace(ApplicationPath, ".")
I'd split both of your paths at the directory level. From there, find the point of divergence and work your way back to the assembly folder, prepending a '../' everytime you pass a directory.
Keep in mind however, that an absolute path works everywhere and is usually easier to read than a relative one. I personally wouldn't show an user a relative path unless it was absolutely necessary.