首页 > 解决方案 > 访问我的项目根目录中的文件夹 - ASP.NET Core 3.1

问题描述

我有一个名为的根文件夹TestLogging,其中包含一个解决方案。我有一个控制台应用程序,它有自己的目录,还有一个测试项目,它也有自己的目录。

在 Windows 资源管理器中,我在根文件夹中手动创建了一个名为 Configuration 的目录TestLogging,其中有一个xml名为Configuration.config.

我正在尝试通过代码访问此路径以引用此文件,而不必使用此文件的绝对路径。

我已经尝试过使用here的各种示例System.IO,它们都指向正在运行的当前项目的构建目录,例如MyConsoleApp\bin\Debug\netcoreapp3.1

以下是我尝试过的一些事情:

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

如果已重复,请提前申请。

标签: asp.net-coresystem.io.directory

解决方案


解决方案

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

测试代码

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

测试结果

在此处输入图像描述

在此处输入图像描述


推荐阅读