C# – Getting the Directory of a Running Executable

I was trying to remember how to get the directory of a running executable and I ran across this stack overflow entry on the subject:

http://stackoverflow.com/questions/1658518/getting-the-absolute-path-of-the-executable-using-c

The answer the question is really embedded in the comments to the answer.  The answer says to use System.Reflection.Assembly.GetExecutingAssembly which will work if you call the method directly from your assembly.  But if you call that from another assembly and it’s not in your executable directory then you’ll get the wrong location.  Anyway, it appears that the correct answer is to use System.Reflection.Assembly.GetEntryAssembly, because it will always return your executable.  However, it returns it as a URI.  So here is a quick method that you can use to return the directory of the current executable that takes the URI into account:

public static DirectoryInfo GetExecutingDirectory()
{
    var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
    return new FileInfo(location.AbsolutePath).Directory;
}

This method returns a DirectoryInfo object which contains just about any information you could want on the executable directory.  If you just want the directory as a string, you can get that from the FullName property on the DirectoryInfo object, or you can modify the function to look like this:

public static string GetExecutingDirectoryName()
{
    var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
    return new FileInfo(location.AbsolutePath).Directory.FullName;
}

Also note that the FullName property returns the directory without a trailing slash.