4

I have the EXE in the following location:

C:\Projects\Bin\Sample.EXE

I want to get the path in C# like this:

C:\Projects\

One way to do this is:

string str = "C:\\Projects\\Bin\\Sample.EXE"
string res = str.Replace("Bin", "")

But this is NOT an efficient way. My Bin folder can be changed to Bin1, Bin2 etc ... So the Bin name is NOT constant. It can be C:\\Projects\\Debug\\Sample.EXE also. Basically, I want to move one level up in the directory structure.

Can you please provide me sample code ?

Here is the sample code I am looking for:

@marc_s code

This is completely different from above two previous questions and I did not find solution to my issue using earlier two links.

2 Answers2

9

Get the location of the currently executing assembly, and go up one level from that directory - like this:

-- get path of the executing assembly
string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

-- get the parent directory for that path
string parentPath = Path.GetFullPath(Path.Combine(currentPath, ".."));
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
1
string path = @"C:\Projects\Bin\Sample.EXE";
FileInfo file = new FileInfo(path);

string res = file.Directory.Parent.FullName;
Console.WriteLine(res); // C:\Projects
poke
  • 369,085
  • 72
  • 557
  • 602
  • I used both of them .... System.Reflection.Assembly.GetExecutingAssembly().Location and string path = @"C:\Projects\Bin\Sample.EXE"; FileInfo file = new FileInfo(path); string res = file.Directory.Parent.FullName; Console.WriteLine(res); // C:\Projects Still I am testing ... – Kishore Babu. Peddi Aug 18 '15 at 20:34