Getting relative path from full path

I need to get a path that excludes the relative path from the full path, they say

Relative path: C: \ User \ Documents \

fullpath, C: \ User \ Documents \ Test \ Folder2 \ test.pdf

I want to get only the path after the relative path ie \ Test \ Folder2 \ test.pdf

how can i achieve this.

I use C # as a programming language

+6
source share
3 answers

You are not talking about the relative, so I will name it in a partial way. If you can be sure that the partial path is part of your full path, this is simple string manipulation:

string fullPath = @"C:\User\Documents\Test\Folder2\test.pdf"; string partialPath = @"C:\User\Documents\"; string resultingPath = fullPath.Substring(partialPath.Length); 

This requires some error checking: it will fail if either fullPath or partialPath is null or both paths are the same length.

+5
source

Hmmmm, but what if the matter is different? Or does one of the paths use short names for its folders? A 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; } 
+2
source

To expand Jan's answer, you can create an extension method for the string class (or the Path class if you want), for example:

 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 have not tested that this extension method works, but should do .

0
source

Source: https://habr.com/ru/post/899690/


All Articles