简体   繁体   中英

Use settings file in .net core 3.1, single file published windows service

How to correctly use JSON settings files in windows services build in 3.1 net core, that are published in a single file.

  1. Publishing as single file, requires you to do two things. First, exclude the settings JSON file from the single file. If you do not do it, it will be unpacked together with the rest, loaded and it will appear to work, if there are default values in it. And second, copy the settings file to the publish directory. You can do this by adding this:
    <ItemGroup>
            <Content Update="appsettings.json">
                <CopyToPublishDirectory>Always</CopyToPublishDirectory>
                <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
            </Content>
    </ItemGroup>

In your pubxml profile. Building it from the interface with: Build > Publish (Project name) will not work. You gotta use the command line from now on.

  1. Once packed into a single file, the base path of your application is changed. Simply placing the JSON files next to your exe will not do the trick. Also, you will be using windows services. Starting the exe is one thing, starting the service is another universe. In most situations you can use the following:
    Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

To get the directory of your single-file packed exe service.

  1. The packed exe checks the temp folder it creates for resources, you need to redirect some of the features to another folder. You will want to do this, at least for your log files and settings. For example, if you want the application to check for JSON files near your exe, you add this:
.ConfigureAppConfiguration((context, config) =>
                {
                    config.SetBasePath(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));                    
                })

in your CreateHostBuilder method.

I hope that this will save you some time. Ive been fighting this all morning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM