Home > other >  Get the current directory of my exe, even when it is launched from another app or shortcut
Get the current directory of my exe, even when it is launched from another app or shortcut

Time:07-29

Solved.

I found out that the "StartIn" variable of a shortcut directly affects the result of the current working directory. That is why no matter what I change in the code or the method I use to find the current directory, the result always says the shortcut's directory.


I am currently trying to get the directory of my exe. I am using Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase) to do that. The problem is that the directory it returns is the directory of the shortcut or app that launched it. While I need the directory of the actual executable.

Tried methods:

  • Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)
  • Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
  • Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
  • AppContext.BaseDirectory
  • Environment.CurrentDirectory

CodePudding user response:

As I already said in the comments AppContext.BaseDirectory has to return the correct path, you are doing something that is unknown to us.

Here a proof that it is working as expected

My WinForms application consists of this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MessageBox.Show(AppContext.BaseDirectory);
    }
}

Here a screenshot as proof:

Then I went ahead and created a shortcut next to the solution:

When I double click the shortcut, a message box pops up with the following content:

As you can see it is as expected the Debug location and not the solution file location.

Edit:

Also changeing "ausführen in" (maybe "start in" or "run in" in english) does NOT contribute to the described behaviour for AppContext.BaseDirectory, as you can see here:

  • Related