Maui Blazor 中文社区 QQ群:645660665

.net6+ 在单文件应用程序中获取程序集位置

一般来说,获取执行程序集的位置,您可以调用:

var executableDirectory = System.Reflection.Assembly.GetExecutingAssembly().Location;

如果发布为单个文件, 会提示如下警告

warning IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'.

需要改为 AppContextBaseDirectory获取当前目录

var executableDirectory = System.AppContext.BaseDirectory;

示例用法

例如,您可以使用此路径来设置当前目录:

var executableDirectory = AppContext.BaseDirectory;
Directory.SetCurrentDirectory(executableDirectory ?? throw new Exception("Could not find out executable directory"));

或者指示配置文件提供者而不改变当前目录:

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.SetBasePath(AppContext.BaseDirectory);
builder.Configuration.AddJsonFile("CustomConfig.json");

参考:

https://www.softwaredeveloper.blog/executing-assembly-location-in-a-single-file-app

posted @ 2024-07-02 06:42  AlexChow  阅读(13)  评论(0编辑  收藏  举报