如何获取.Net Core控制台应用程序的.exe文件所在目录的路径?

How to get the path of the directory where the .exe file for a .Net Core console application is located?

我想创建一个由 Windows 任务计划程序获取 运行 的 .Net Core 控制台应用程序。在这个控制台应用程序中,我想找到应用程序的 .exe 文件所在目录的路径。

我通过 运行 在命令提示符中输入这行代码来发布应用程序以创建 .exe 文件: dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true

我认为这可能与下面概述的奇怪行为有关。

我遇到的问题是,当我运行.exe文件时,它获取的路径不是它所在文件夹的路径。

为了演示这一点,我编写了这个控制台应用程序:

//program.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;

namespace PathTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Write(Directory.GetCurrentDirectory());

            Write(Assembly.GetExecutingAssembly().Location);

            Write(Assembly.GetExecutingAssembly().CodeBase);

            Write(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            Write(AppDomain.CurrentDomain.BaseDirectory);

            Write(Environment.GetCommandLineArgs()[0]);

            Write(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));

            Write(Process.GetCurrentProcess().MainModule.FileName);

            Write(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            Console.ReadKey();
        }

        readonly static Action<string> Write = (str) =>
        {
            Console.WriteLine(str);
            Console.WriteLine("");
        };
    }
}

当我调试这个程序时,我得到了这个输出: debug image

当我 运行 .exe 文件时,我得到以下输出: manual run

当我使用 Windows 任务计划程序 运行 .exe 文件时,我得到以下输出: task scheduler image

我想知道的是:我应该用什么代码来获取.exe文件所在目录的路径?

为什么要返回临时文件夹的路径?

由于这个问题,我找到了答案:https://github.com/dotnet/runtime/issues/13051

您必须使用:Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)