1

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.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
TheAuzzieJesus
  • 587
  • 9
  • 23
  • `"..\..\"` - your exe doesn't "know" about the folder-structure of its source code. – Blorgbeard Aug 08 '16 at 01:04
  • 1
    Possible duplicate of [Best way to get application folder path](http://stackoverflow.com/questions/6041332/best-way-to-get-application-folder-path) – M.Hassan Aug 08 '16 at 01:14
  • I had a quick look at that question before I posted my own and found it didn't have an appropriate answer for me. – TheAuzzieJesus Aug 08 '16 at 01:26

2 Answers2

1

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
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

you can use this code

string path = System.AppDomain.BaseDirectory + "//bin//debuge//filename.exe";
hamid
  • 59
  • 2
  • 9
  • Is it possible to use this in a static context? – TheAuzzieJesus Aug 08 '16 at 01:07
  • 1
    I don't believe this is true. I am receiving Error (CS0120) : An object reference is required for the non-static field, method, or property 'AppDomain.BaseDirectory' when using this in a static class. Any chance of fixing this? – TheAuzzieJesus Aug 08 '16 at 01:15
  • While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Aug 08 '16 at 04:55