Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure self-contained single-file program?

Tags:

c#

.net-core

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)?

like image 819
SET Avatar asked Jul 26 '19 15:07

SET


1 Answers

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();
like image 149
Paul Avatar answered Oct 31 '22 03:10

Paul