I have to get the path excluding the relative path from the full path, say
The relative path is ,C:\User\Documents\
fullpath ,C:\User\Documents\Test\Folder2\test.pdf
I want to get only the path after the relative path i.e \Test\Folder2\test.pdf
how can i achieve this.
I am using C# as the programming language
You are not talking about relative, so i will call it partial path. If you can be sure that the partial path is part of your full path its a simple string manipulation:
string fullPath = @"C:\User\Documents\Test\Folder2\test.pdf";
string partialPath = @"C:\User\Documents\";
string resultingPath = fullPath.Substring(partialPath.Length);
This needs some error checking though - it will fail when either fullPath or partialPath is null or both paths have the same length.
Hmmmm, but what if the case is different? Or one of the path uses short-names for its folders? The more complete solution would be...
public static string GetRelativePath(string fullPath, string containingFolder,
bool mustBeInContainingFolder = false)
{
var file = new Uri(fullPath);
if (containingFolder[containingFolder.Length - 1] != Path.DirectorySeparatorChar)
containingFolder += Path.DirectorySeparatorChar;
var folder = new Uri(containingFolder); // Must end in a slash to indicate folder
var relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
if (mustBeInContainingFolder && relativePath.IndexOf("..") == 0)
return null;
return relativePath;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With