How can I get my .NET Core 3 single file app to find the appsettings.json file?

18,320

Solution 1

I found an issue on GitHub here titled PublishSingleFile excluding appsettings not working as expected.

That pointed to another issue here titled single file publish: AppContext.BaseDirectory doesn't point to apphost directory

In it, a solution was to try Process.GetCurrentProcess().MainModule.FileName

The following code configured the application to look at the directory that the single-executable application was run from, rather than the place that the binaries were extracted to.

config.SetBasePath(GetBasePath());
config.AddJsonFile("appsettings.json", false);

The GetBasePath() implementation:

private string GetBasePath()
{
    using var processModule = Process.GetCurrentProcess().MainModule;
    return Path.GetDirectoryName(processModule?.FileName);
}

Solution 2

If you're okay with having files used at runtime outside of the executable, then you could just flag the files you want outside, in csproj. This method allows for live changes and such in a known location.

<ItemGroup>
    <None Include="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
    </None>
    <None Include="appsettings.Development.json;appsettings.QA.json;appsettings.Production.json;">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
      <DependentUpon>appsettings.json</DependentUpon>
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
    </None>
  </ItemGroup>

  <ItemGroup>
    <None Include="Views\Test.cshtml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
    </None>
  </ItemGroup>

If this is not acceptable, and must have ONLY a single file, I pass the single-file-extracted path as the root path in my host setup. This allows configuration, and razor (which I add after), to find its files as normal.

// when using single file exe, the hosts config loader defaults to GetCurrentDirectory
            // which is where the exe is, not where the bundle (with appsettings) has been extracted.
            // when running in debug (from output folder) there is effectively no difference
            var realPath = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;

            var host = Host.CreateDefaultBuilder(args).UseContentRoot(realPath);

Note, to truly make a single file, and no PDB, you'll also need:

<DebugType>None</DebugType>

Solution 3

My application is on .NET Core 3.1, is published as a single file and runs as a Windows Service (which may or may not have an impact on the issue).

The proposed solution with Process.GetCurrentProcess().MainModule.FileName as the content root works for me, but only if I set the content root in the right place:

This works:

Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseContentRoot(...);
        webBuilder.UseStartup<Startup>();
    });

This does not work:

Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .UseContentRoot(...)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    });

Share:
18,320
Jason Yandell
Author by

Jason Yandell

Updated on July 04, 2022

Comments

  • Jason Yandell
    Jason Yandell almost 2 years

    How should a single-file .Net Core 3.0 Web API application be configured to look for the appsettings.json file that is in the same directory that the single-file application is built to?

    After running

    dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
    

    The directory looks like this:

    XX/XX/XXXX  XX:XX PM    <DIR>          .
    XX/XX/XXXX  XX:XX PM    <DIR>          ..
    XX/XX/XXXX  XX:XX PM               134 appsettings.json
    XX/XX/XXXX  XX:XX PM        92,899,983 APPNAME.exe
    XX/XX/XXXX  XX:XX PM               541 web.config
                   3 File(s)     92,900,658 bytes
    

    However, attempting to run APPNAME.exe results in the following error

    An exception occurred, System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\Users\USERNAME\AppData\Local\Temp\.net\APPNAME\kyl3yc02.5zs\appsettings.json'.
       at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)
       at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
       at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
       at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
       at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
       at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
       at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
    ...
    

    I tried solutions from a similar, but distinct question, as well as other Stack Overflow questions.

    I attempted to pass the following to SetBasePath()

    • Directory.GetCurrentDirectory()

    • environment.ContentRootPath

    • Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)

    Each led to the same error.

    The root of the issue is that the PublishSingleFile binary is unzipped and run from a temp directory.

    In the case of this single file app, the location it was looking appsettings.json was the following directory:

    C:\Users\USERNAME\AppData\Local\Temp\.net\APPNAME\kyl3yc02.5zs
    

    All of the above methods point to the place that the file is unzipped to, which is different than the place it was run from.

  • Paul Cohen
    Paul Cohen over 4 years
    How does Views\Test.cshtml in your example get on the target computer? I have image and dictionary files that I need to open based on Culture,
  • Ronald Swaine
    Ronald Swaine over 4 years
    @PaulCohen I would typically deploy all files from the published output location using SCP. With only the changes in csproj (first example) any APIs that are using the default root content directory will need to have their files available in the working directory. It sounds like you need to use the 2nd example, to get the real path of the extracted content, so that way you can access the images from a full path, or by having the content root set correctly so that ~/... paths to images can be used in razor.
  • Paul Cohen
    Paul Cohen over 4 years
    My background is in embedded applications so a single binary is usually burned into rom. What I am realizing is there the Exe that I share in some kind of self extracting “zip like” file. All my data files are in there and when the application is run everything is extracted to a temp directly. If I find that I can find my data files. It also means I need some logic so I can Debug in VS where the data is somewhere else.
  • Going-gone
    Going-gone over 4 years
    I have this setup currently, and it randomly stopped finding the files.
  • Aaron Hudon
    Aaron Hudon over 4 years
    This answer, plus @ronald-swaine below is perfect. The appsettings are excluded from the bundled exe, and the publishing task places the appsettings files alongside the bundled exe.
  • granadaCoder
    granadaCoder almost 4 years
    "var realPath" You rock the suburbs. I've added an answer to expound on where to set the value.......but wow..this was a lifesaver. Thanks.
  • user685590
    user685590 over 3 years
    I had the same error. My problem was actually at the deployment stage - I have changed appSettings.json to appsettings.json but Github commit did not care about that case change (needed to change local settings, just something to check)
  • John Baughman
    John Baughman over 3 years
    I've been fighting this for a few days now. Thanks for your solution. I do feel it's a bit of an odd workaround for something that should "just work". And everything behaves much differently in .NET 5 vs .NET Core 3.1. This: Path.Combine(AppContext.BaseDirectory, Assembly.GetExecutingAssembly().ManifestModule.Name) works in the VS2019 preview in debug, but after publishing to a single file (no trimming, no Ready-To-Run) it returns " System.IO.FileNotFoundException: The system cannot find the file specified. (0x80070002)". Seems something is missing to me...
  • hB0
    hB0 over 3 years
    This needs to be fixed. We should not write the code to determine also the Environment and read up/aggregate each appsettings json files. Not good. This is not a good work around. Must look up and update or create a new GitHub issue at MS.
  • hB0
    hB0 over 3 years
    First solution, keeping appsettings file outside is what I use and it does not work as expected. When you have single file, it extracts on to a temp location under User profile in windows, and there it also has appsettings file extracted as well as to the original location; but the run-path at exec time is set to the temp directory's location; and therefore kills the purpose. SingleFile is just a cosmetic change; rather I would avoid it at the server environment.
  • hB0
    hB0 over 3 years
    ever changing behavior of .net core system call, changes btw sub-versions of net core github.com/dotnet/runtime/issues/3704#issuecomment-607103702 meaning this runtime is not-usable under shared environment setup unlike full .net fw version (which does not break main fw apis/services)
  • hB0
    hB0 over 3 years
    MS: "This issue is fixed in .net5" - So .NET 3.1 is let down? REF: github.com/dotnet/runtime/issues/3704#issuecomment-651210020