Get to a Folder in the Root of my Project - ASP.NET Core 3.1

2.1k views Asked by At

I have a root folder called TestLogging that contains a solution. I have a console app, which has its own directory, and a test project which also has its own directory.

In Windows explorer I have manually created a directory called Configuration in the root folder TestLogging, which has an xml file named Configuration.config.

I am trying to get to this path via code to reference this file, without having to use an absolute path to this.

I have tried variations of examples from here using System.IO and they all point to the build directory of the current project that is being run e.g. MyConsoleApp\bin\Debug\netcoreapp3.1

Here are some of the things I've tried:

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

// this does the same as above!
string pathToConsoleApp = Path.GetFullPath(AppContext.BaseDirectory);

// very similar to the other two!
var projectPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)));

Appoligies in advanced if this has been duplicated.

1

There are 1 answers

2
Michael Wang On BEST ANSWER

Solution

string configpPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Configuration.config.xml");

Test code

class Program
{
    static void Main(string[] args)
    {
        string defaultPath = System.IO.Directory.GetCurrentDirectory();

        // this does the same as above!
        string pathToConsoleApp = Path.GetFullPath(AppContext.BaseDirectory);

        // very similar to the other two!
        var projectPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)));

        string configpPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Configuration.config.xml");


        Console.WriteLine("Hello World!");
        Console.WriteLine("defaultPath:   " + defaultPath);
        Console.WriteLine("pathToConsoleApp:   " + pathToConsoleApp);
        Console.WriteLine("projectPath:   " + projectPath);
        Console.WriteLine("configpPath:   " + configpPath);
    }
}

Test result

enter image description here

enter image description here