Search code examples
c#openfiledialog

Get the base path of all files in a project in?


Let's say I have a file path of:

C:\Users\my_name\Desktop\my_project\bin\debug\my_project.exe

How can I get the following file path to use in an OpenFileDialog?

C:\Users\my_name\Desktop\my_project\

EDIT:

I've tried the following..

var path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent?.ToString();

var path = Assembly.GetExecutingAssembly().CodeBase;

But both return incorrect values.


Solution

  • You can use the following logic:

    DirectoryInfo Di = Directory.GetParent(@"C:\Users\my_name\Desktop\my_project\bin\debug\my_project.exe");
    // Which will give you the debug folder
    int DirectoryLevel = 3;
    for (int i = 1; i < DirectoryLevel; i++)
    {
        Di = Di.Parent;
        // Which will give you the bin fodler when i =1
        // Which will give you the my_project folder when i =2
    }
    string currentDirectory = Di.FullName; // Give the path