Get current application directory

Often when I write apps, I come across a situation where in I need to store some temporary files. Say, I need to run a command through System.Diagnostics.Process. This command requires a path to store the output as a file though an /o: parameter. For ages I used to use Assembly.GetExecutingAssembly().Location to get the directory of the current app.

This often gets very hairy as the current executing assembly will change if you are invoking your application through an external service. Running unit test cases on this app gets trickier as testing frameworks like NUnit create temporary DLLs at temporary locations. I saw this post that uses Assembly.GetExecutingAssembly().CodeBase to make the application behave better.

Simple code but very effective:

static public string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.