How to get the application’s directory in C#

Just a short one today…

I always used to forget how to get the path of the directory that my code is running in, and although I did remember it eventually, I also recall that along the way, I found some wrong, or at least incomplete answers. So here is the code I use…

Firstly, here’s a way that works for console applications. I don’t normally do this anymore, since it doesn’t work for everything, but just to make this complete, here it is anyway.

using System;
using System.IO;

namespace Demo
{
    class Example
    {
        private static void Main()
        {
            var directory = Path.GetDirectoryName(
                Environment.GetCommandLineArgs()[0]);

            // Your code here...
        }
    }
}

Notice that in the Main method, I removed the default arguments. They’re not necessary, and besides, they may behave differently when debugging and at runtime. The Environment.GetCommandLineArgs method fetches your arguments from the system; the first argument being the full path and name of your program.

But that only works for console applications. There’s also a method that only works on Windows Forms: Application.StartupPath. But what we need is a method that works in all cases, and here it is:

using System;
using System.IO;
using System.Reflection;

namespace Demo
{
    class Example
    {
        public Example()
        {
            var directory = new Uri(Path.GetDirectoryName(
                Assembly.GetExecutingAssembly().CodeBase))
                .LocalPath;
        }
    }
}

In order not to have you need to scroll, I wrapped those lines and added the necessary namespaces to the using clauses above. (I don’t normally do that, and this is essentially one line of code.)

This gets the application name using Reflection, and then extracts the directory part. The reason I use a Uri is that it gets the path in HTML-encoded form, and not all other code will understand it, so I just use it to extract the actual local path. This works no matter what kind of program you are writing.

Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s