8

I want to get the path of my app like: "\\ProgramFiles\\myApp", I try to use the following code:


string path = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;

But it returns a path which has "\\myapp.exe" at the end.

I also tried:


string path = System.IO.Directory.GetCurrentDirectory();

But it throws an “NotSupportedException”.

Is there any way to get a path without .exe at the end?

ctacke
  • 66,480
  • 18
  • 94
  • 155
Chilly Zhong
  • 16,763
  • 23
  • 77
  • 103

7 Answers7

19

Application.StartupPath should do that for you.

Update: from you edit I see that you are running on Compact Framework. Then Application.StartupPath will not work. This is the construct that I usually use then:

private static string GetApplicationPath()
{
    return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
}
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
11
path = System.IO.Path.GetDirectoryName( path );
Nasreddine
  • 36,610
  • 17
  • 75
  • 94
Dan Byström
  • 9,067
  • 5
  • 38
  • 68
3

More simple than the rest:

using System.IO;
using System.Reflection;
...
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Chris
  • 27,596
  • 25
  • 124
  • 225
1

You can use Path.GetDirectoryName(string) method passing your original path string as parameter for this. What problem are you trying to solve? Maybe you really need something like working directory?

okutane
  • 13,754
  • 10
  • 59
  • 67
  • Thank you and danbyStrom, your guide works well. I'm trying to play sound using the wav file in my app's directory, so I need its directory(without app.exe). – Chilly Zhong May 19 '09 at 07:07
0
Path.GetFileNameWithoutExtension(path);
JP Alioto
  • 44,864
  • 6
  • 88
  • 112
0

What about using a FileInfo object to extract the directory name?

In Vb.Net:

fi = New FileInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
path = fi.DirectoryName
JYelton
  • 35,664
  • 27
  • 132
  • 191
amrtn
  • 587
  • 4
  • 10
  • "Location" is not found in C# app, but everything in () can be replaced by the filepath I wrote and it works. Thanks. – Chilly Zhong May 19 '09 at 07:03
  • Doesn't `GetExecutingAssembly` need `()`? e.g. `GetExecutingAssembly()`, or is that just **C#**? – Momoro May 06 '20 at 08:36
0

If its an exe as in your case use:

    // Summary:
    //     Gets the path for the executable file that started the 
    //     application, not including the executable name.    
    Application.StartupPath
NileshChauhan
  • 5,469
  • 2
  • 29
  • 43