How do I find the parent directory in C#?

后端 未结 15 683
旧时难觅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:27

    Like this:

    System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory);
    string parentDirectory = myDirectory.Parent.FullName;
    

    Good luck!

    0 讨论(0)
  • 2020-11-29 05:30

    If you append ..\.. to your existing path, the operating system will correctly browse the grand-parent folder.

    That should do the job:

    System.IO.Path.Combine("C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug", @"..\..");
    

    If you browse that path, you will browse the grand-parent directory.

    0 讨论(0)
  • 2020-11-29 05:31

    To get your solution try this

    string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
    
    0 讨论(0)
  • 2020-11-29 05:32

    Directory.GetParent is probably a better answer, but for completeness there's a different method that takes string and returns string: Path.GetDirectoryName.

    string parent = System.IO.Path.GetDirectoryName(str_directory);
    
    0 讨论(0)
  • 2020-11-29 05:33

    No one has provided a solution that would work cross-form. I know it wasn't specifically asked but I am working in a linux environment where most of the solutions (as at the time I post this) would provide an error.

    Hardcoding path separators (as well as other things) will give an error in anything but Windows systems.

    In my original solution I used:

    char filesep = Path.DirectorySeparatorChar;
    string datapath = $"..{filesep}..{filesep}";
    

    However after seeing some of the answers here I adjusted it to be:

    string datapath = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory()).FullName).FullName; 
    
    0 讨论(0)
  • 2020-11-29 05:34

    You shouldn't try to do that. Environment.CurrentDirectory gives you the path of the executable directory. This is consistent regardless of where the .exe file is. You shouldn't try to access a file that is assumed to be in a backwards relative location

    I would suggest you move whatever resource you want to access into a local location. Of a system directory (such as AppData)

    0 讨论(0)
提交回复
热议问题