.NET CORE 3 Windows 服务的基本路径返回 C:\Windows\System32,但实际文件夹是 D:\MyCustomService

.NET CORE 3 The base path of a Windows Service is returning C:\Windows\System32, But actual folder is D:\MyCustomService

这里 AppContext.BaseDirectory 总是返回 C:\Windows\System32 但我们期待 D:\MyCustomService - 我们有实际文件的地方。

请找到我的以下代码。你能建议哪里出了问题吗?我也试过所有其他选项,如 CurrentDirectory、System.Reflection.Assembly.GetEntryAssembly().Location、Process.GetCurrentProcess().MainModule.FileName;等等

我们已经使用以下命令安装了服务器

sc create "myServiceName" binPath="D:\MyCustomService\myServiceName.exe"

public class Program
{
        public static void Main(string[] args)
        {
            const string loggerTemplate = @"{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level:u4}]<{ThreadId}> [{SourceContext:l}] {Message:lj}{NewLine}{Exception}";

            var baseDir = AppContext.BaseDirectory;

            Console.WriteLine(baseDir);

            var logfile = Path.Combine(baseDir, "App_Data", "logs", "log.txt");
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                .Enrich.With(new ThreadIdEnricher())
                .Enrich.FromLogContext()
                .WriteTo.Console(LogEventLevel.Information, loggerTemplate, theme: AnsiConsoleTheme.Literate)
                .WriteTo.File(logfile, LogEventLevel.Information, loggerTemplate, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 90)
                .CreateLogger();
            try
            {
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application terminated unexpectedly");
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            })
            .UseWindowsService();
}

显然你不能,因为 Windows 服务在你提到的文件夹中运行,阅读 Microsoft documentation:

Don't attempt to use GetCurrentDirectory to obtain a resource path because a Windows Service app returns the C:\WINDOWS\system32 folder as its current directory.