Search code examples
c#.netnunitcodebase

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


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)


Solution

  • 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;
    

    The LocalPath includes the assembly's file name, e.g.,

    D:\projects\MyApp\MyApp\bin\debug\MyApp.exe
    

    If you want the assembly's directory, then use System.IO.Path.GetDirectoryName():

    string localDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
    

    which will give you:

    D:\projects\MyApp\MyApp\bin\debug