views:

903

answers:

7

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?

+7  A: 

path = System.IO.Path.GetDirectoryName( path );

danbystrom
+4  A: 

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
Sorry for the confusion and thanks for your quick answer ;P
iPhoney
+1  A: 

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?

Dmitriy Matveev
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).
iPhoney
A: 
Path.GetFileNameWithoutExtension(path);
JP Alioto
Thanks, but this will return the file's name "myApp" just like the method's name mentions. Thanks for the guide on this method anyway.
iPhoney
Shucks! That's what I thought you wanted. :)
JP Alioto
A: 

¿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
amartin
"Location" is not found in C# app, but everything in () can be replaced by the filepath I wrote and it works. Thanks.
iPhoney
A: 

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
nils_gate
A: 

More simple than the rest:

using System.IO;
using System.Reflection;
...
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Chris
ummm...it's simple but "Location" is not found(at least in Windows Mobile app).
iPhoney