Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the relative path from the full path

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

like image 236
Selwyn Avatar asked Oct 20 '11 11:10

Selwyn


2 Answers

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.

like image 76
Jan Avatar answered Oct 18 '22 07:10

Jan


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;
}
like image 37
Gabe Halsmer Avatar answered Oct 18 '22 08:10

Gabe Halsmer