How do I find the parent directory in C#?

后端 未结 15 693
旧时难觅i
旧时难觅i 2020-11-29 05:04

I use this code for finding the debug directory

public string str_directory = Environment.CurrentDirectory.ToString();

\"C:\\\\Us

15条回答
  •  清酒与你
    2020-11-29 05:25

    I've found variants of System.IO.Path.Combine(myPath, "..") to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.

    Path.Combine makes sure you never go wrong with slashes.

    .. behaves exactly like it does everywhere else in Windows. You can add any number of \.. to a path in cmd or explorer and it will behave exactly as I describe below.

    Some basic .. behavior:

    1. If there is a file name, .. will chop that off:

    Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..") => D:\Grandparent\Parent\

    1. If the path is a directory, .. will move up a level:

    Path.Combine(@"D:\Grandparent\Parent\", "..") => D:\Grandparent\

    1. ..\.. follows the same rules, twice in a row:

    Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", @"..\..") => D:\

    1. And this has the exact same effect:

    Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..") => D:\Grandparent\ Path.Combine(@"D:\Grandparent\Parent\", "..", "..") => D:\

提交回复
热议问题