Wednesday, May 22, 2024

Build Action appsettings


In .NET projects, the appsettings.json file is used to store configuration data. The "Build Action" property of files in a .NET project determines how the file is treated by the build process. 

This ensures that the file is included in the output directory of the build and can be read at runtime for configuration purposes.

To set the "Build Action" to "Content" for appsettings.json (or any file) in Visual Studio:

  1. Right-click on the appsettings.json file in the Solution Explorer.
  2. Select "Properties" from the context menu.
  3. In the Properties window, find the "Build Action" property.
  4. Set the "Build Action" to "Content".

When set to "Content", the file is copied to the output directory (e.g., bin\Debug\netcoreapp3.1\) during the build if the "Copy to Output Directory" property is also set appropriately. The "Copy to Output Directory" property has a few options:

  1. Do not copy: The file is not copied to the output directory automatically.
  2. Copy always: The file is always copied to the output directory, overwriting any existing file with the same name.
  3. Copy if newer: The file is only copied if it has been modified since the last build that resulted in a copy operation.

If the application setting is set as 'Do not copy', dotnet run will throw the below error

System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. 

No comments:

Post a Comment