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
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;
}