C# Path of dll vs. Application path vs. EntryAssembly path vs. Form path

OK, I have stumbled on this one a few times so I thought I would blog it up so that I had a place to come and find the answer. The problem most recently was an application I wrote that I use as a command line tool, but other times as a class that hits a constructor. Either way a property file is needed, and depending on the way I call it I had trouble finding the path to the config…

The problem is, when you use Microsoft Visual Studio to launch the debugger, the Application.StartupPath can’t be relied upon, as it points to the Studio directory. At run time it might work, but not for the case I had in mind where I needed to know where the DLL itself was.

So you can use this:

System.Windows.Forms.Application.StartupPath

But that is for a windows form startup path – useful, but not for me.

This will give you the directory the app started in (but again, it may be a Visual Studio directory if debugging):

Application.StartupPath

And this will give you the process executable in the default application domain, or the first executable that was executed by AppDomain.ExecuteAssembly – again, not what I needed:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)

Finally, the winner is (and look closely – GetExecutingAssembly vs. GetEntryAssembly)

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)

This snip allowed me to find the directory where the DLL was currently executing, and thus the config that sits next to it. So many ways to get at run-time information! Hope that helps you!!