Search code examples
c#.netpath

How to make an absolute path relative to a particular folder?


For example, how can I make this

"C:\RootFolder\SubFolder\MoreSubFolder\LastFolder\SomeFile.txt"

relative to this folder

"C:\RootFolder\SubFolder\"

if the expected result is

"MoreSubFolder\LastFolder\SomeFile.txt"

Solution

  • Yes, you can do that, it's easy, think of your paths as URIs:

    Uri fullPath = new Uri(@"C:\RootFolder\SubFolder\MoreSubFolder\LastFolder\SomeFile.txt", UriKind.Absolute);
    Uri relRoot = new Uri(@"C:\RootFolder\SubFolder\", UriKind.Absolute);
    
    string relPath = relRoot.MakeRelativeUri(fullPath).ToString();
    // relPath == @"MoreSubFolder\LastFolder\SomeFile.txt"