150

This question already has an answer here:

how can I get my .exe path because if I copy my .exe I can get my new path ?

4 답변


188

System.Reflection.Assembly.GetEntryAssembly().Location;


  • I only wanted the Path but I see this command gives me path + filename of the exe. :-( On the other Hand GetEntryAssembly().Location gives the path with "file://" - What I needed was AppDomain.CurrentDomain.BaseDirectory - user799821
  • This does not work in a Unit Test project. GetEntryAssembly() is null. - Eric J.
  • System.Reflection.Assembly.GetExecutingAssembly().Location returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory. System.Reflection.Assembly.GetExecutingAssembly().CodeBase will return the 'permenant' path of the assembly. - Cyrus
  • @user799821 Just use Path.GetDirectoryName to get the folder without the filename. - ProfK
  • @ProfK: thanks, that was exactly what I needed. Full solution worked for me: System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) - SnookerC

95

In addition:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location


  • AppDomain.CurrentDomain.BaseDirectory works in a Unit Test project. - Eric J.
  • Assembly.GetEntryAssembly().Location works for me. The first one has file;\ while the second one provides the absolute file path of the executing .exe. Add System.IO.Path.GetDirectoryName() to get the path only - CraftedGaming

55

In a Windows Forms project:

For the full path (filename included): string exePath = Application.ExecutablePath;
For the path only: string appPath = Application.StartupPath;


  • "Application.StartupPath will be effected by "Working Directory" if it's set in the exe shortcut, or the process is started from another apps." - Pedro77

2

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;


  • That's not really correct answer. It will give you a string like "file://foo" - dyatchenko
  • Also it will end up with ArgumentException in System.IO.Path.GetDirectoryName - benderto

Linked


Related

Latest