0

Just now I have a path like this MyDir\Inner\Foo and I want to be able to transform it into MyDir\Inner.

My idea was to use Path.Combine(myRelativeDir, "..") and then (for user display purposes) resolve it to remove the ...

When I've researched this online, I can only seem to find solutions that involve doing a Path.GetFullPath after Path.Combine to resolve it, but this does not help me as it results in something like C:\RootFolders\ThatIWantToHide\MyDir\Inner and I don't want to show a full path.

Is there anything in the standard libraries that allows this or will I have to resort to string manipulation of some sort?

In summary

Input: MyDir\Inner\Foo (relative path)

Desired Output: MyDir\Inner (relative path maintained)

Undesired Output: C:\RootFolders\ThatIWantToHide\MyDir\Inner (relative path lost)

Undesired Output: Inner (just the name, not the relative path)

adjan
  • 13,371
  • 2
  • 31
  • 48
Geesh_SO
  • 2,156
  • 5
  • 31
  • 58
  • I might be missing something but looks like you need [Directory.GetParent](https://msdn.microsoft.com/en-us/library/system.io.directory.getparent.aspx) – Vlad Stryapko Jul 11 '17 at 20:41
  • Hi Vlad, I just gave it a shot but it still seems to return an absolute path. https://dotnetfiddle.net/IBK6Ba – Geesh_SO Jul 11 '17 at 20:46
  • Please check my answer. You can access Name property, which returns a relative path. FullName has an absolute one. – Vlad Stryapko Jul 11 '17 at 20:48

2 Answers2

3

This gets the parent and maintains relative path info:

 Console.WriteLine(Path.GetDirectoryName(@".\bin\debug"));
michalh
  • 2,907
  • 22
  • 29
0

You may use the Path.GetFullPath to get the absolute path, and than use the answer to this post to change it to a relative path. In short, the code uses Uri.MakeRelativeUri() method.

LiborV
  • 164
  • 4