Selwyn
Selwyn

Reputation: 1621

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

Upvotes: 6

Views: 3990

Answers (3)

Gabe Halsmer
Gabe Halsmer

Reputation: 868

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

Upvotes: 2

Darbio
Darbio

Reputation: 11418

To expand on Jan's answer, you could create an extension method on the string class (or the Path class if you wanted) such as:

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static string GetPartialPath(this string fullPath, string partialPath)
        {
            return fullPath.Substring(partialPath.Length)
        }
    }   
}

And then use:

using ExtensionMethods;
string resultingPath = string.GetPartialPath(partialPath);

I haven't tested that this extension method works, but it should do.

Upvotes: 0

Jan
Jan

Reputation: 16038

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.

Upvotes: 5

Related Questions