Finding the path to the running assembly

There are several ways to get the path to the running assembly in c#.
I used to do something like

Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

However when running unit tests etc this would cause pain and some old dirty solutions included injecting a hardcoded path for testing.

I recently found a much better way to do this when googling around on the Internet:

Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
String path = System.IO.Path.GetDirectoryName(uri.LocalPath);

I can´t remember where I found but now it is here anyway :)

Comments are closed.