How to get the relative path (folder the executable was launched in) as a string in C#?

Well, lets say you launch an application and you want to know the relative path.

In C# you can use the System.Reflection.Assembly.GetExecutingAssembly().Location value. I have searched through many online sites that tell different ways, and some of the more experienced C# developers say that some of the other ways are not always accurate or won’t always work, while this one should always work.

So if you make a class and add two String class variables, you can use this function to populate them: Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)


        private void GetPaths()
        {
            mExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            mExecutableRootDirectory = System.IO.Path.GetDirectoryName(mExecutablePath);
        }

Ok, so I like to make sure any newbie can pull this off, so the whole file with it working (using a New WPF project):

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestPath
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        DataSet mDataSet;
        String mExecutablePath;
        String mExecutableRootDirectory;

        public Window1()
        {
            GetPaths();
            InitializeComponent();
        }

        private void GetPaths()
        {
            mExecutablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            mExecutableRootDirectory = System.IO.Path.GetDirectoryName(mExecutablePath);
        }
    }
}

One Comment

  1. Rhyous says:

    I am not sure this existed when I first wrote this post, but you can now do this as well:

    AppDomain.CurrentDomain.BaseDirectory;
    

    The above options didn't work in an IIS hosted WCF service.

Leave a Reply

How to post code in comments?