I am experimenting with .Net Core 3
trimmed single-file publishing creating a simple console application and using this to publish:
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true /p:PublishTrimmed=true
Configuration is done with the standard appsettings.json
and ConfigurationBuilder
from Microsoft.Extensions.Configuration.Json
.
The problem is the config file is packaged with the whole app and so is unavailable - it can be accessed in the temp dir created when running the program but that is not very useful for a regular user.
I found out that you can exclude files from the packaging process by editing the csproj file or with a custom publishing profile
<ItemGroup>
<None Update="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</None>
</ItemGroup>
This does output the appsettings file in the publish dir however it is not used when running the application - an empty config file is created and used instead. Is there any way to do this "properly" since documentation is kinda lacking on the issue or should I just manually parse the file I expect to be in the starting directory (which itself was a hassle to find because Assembly.Get###Assembly
were all returning the temp dir)?
I've found that adding this to the ConfigurationBuilder() before the AddJsonFile() seems to do the trick:
.SetBasePath(Environment.CurrentDirectory)
i.e.:
var configurationRoot = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appSettings.json", optional: false)
.Build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With