Getting the relative path from the full path

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