.net6+ 在單檔案應用程式中獲取程式集位置

AlexChow發表於2024-07-02

一般來說,獲取執行程式集的位置,您可以呼叫:

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

相關文章