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:


        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);
        }
    }
}

Leave a Reply