How do you get the current project directory from C# code when creating a custom MSBuild task?


Instead of running an external program with its path hardcoded, I would like to get the current Project Dir. I'm calling an external program using a process in the custom task.

How would I do that? AppDomain.CurrentDomain.BaseDirectory just gives me the location of VS 2008.

5/3/2009 8:14:58 AM

Accepted Answer

You can try one of this two methods.

string startupPath = System.IO.Directory.GetCurrentDirectory();

string startupPath = Environment.CurrentDirectory;

Tell me, which one seems to you better

5/3/2009 8:32:53 AM

If a project is running on an IIS express, the Environment.CurrentDirectory could point to where IIS Express is located ( the default path would be C:\Program Files (x86)\IIS Express ), not to where your project resides.

This is probably the most suitable directory path for various kinds of projects.


This is the MSDN definition.

Gets the base directory that the assembly resolver uses to probe for assemblies.


This will also give you the project directory by navigating two levels up from the current executing directory (this won't return the project directory for every build, but this is the most common).


Of course you would want to contain this inside some sort of validation/error handling logic.


If you want ot know what is the directory where your solution is located, you need to do this:

 var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
            if (parent != null)
                var directoryInfo = parent.Parent;
                string startDirectory = null;
                if (directoryInfo != null)
                    startDirectory = directoryInfo.FullName;
                if (startDirectory != null)
                { /*Do whatever you want "startDirectory" variable*/}

If you let only with GetCurrrentDirectory() method, you get the build folder no matter if you are debugging or releasing. I hope this help! If you forget about validations it would be like this:

var startDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;

I was looking for this too. I've got a project that runs HWC, and I'd like to keep the web site out of the app tree, but I don't want to keep it in the debug (or release) directory. FWIW, the accepted solution (and this one as well) only identifies the directory the executable is running in.

To find that directory, I've been using

string startupPath = System.IO.Path.GetFullPath(".\\").

Based on Gucu112's answer, but for .NET Core Console/Window application, it should be:

string projectDir = 
    Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));

I'm using this in a xUnit project for a .NET Core Window Application.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]