How can I convert Assembly.CodeBase into a filesystem path in C#?

Dylan Beattie picture Dylan Beattie · Nov 5, 2010 · Viewed 18.2k times · Source

I have a project that stores templates in a \Templates folder next to the DLLs and EXE.

I want to determine this file path at runtime, but using a technique that will work inside a unit test as well as in production (and I don't want to disable shadow-copying in NUnit!)

Assembly.Location is no good because it returns the shadow-copied assembly's path when running under NUnit.

Environment.CommandLine is also of limited use because in NUnit et al it returns the path to NUnit, not to my project.

Assembly.CodeBase looks promising, but it's a UNC path:

file:///D:/projects/MyApp/MyApp/bin/debug/MyApp.exe

Now I could turn this into a local filesystem path using string manipulation, but I suspect there's a cleaner way of doing it buried in the .NET framework somewhere. Anyone know a recommended way of doing this?

(Throwing an exception if the UNC path is not a file:/// URL is absolutely fine in this context)

Answer

Polyfun picture Polyfun · Nov 5, 2010

You need to use System.Uri.LocalPath:

string localPath = new Uri("file:///D:/projects/MyApp/MyApp/bin/debug/MyApp.exe").LocalPath;

So if you want the original location of the currently executing assembly:

string localPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;