Reputation: 715
I've encountered a behaviour I don't understand when it comes to ASP.NET Core.
While working with console applications in order to read a config file I copy it to an output directory in the following way:
<ItemGroup>
<Content Include="mysettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
Otherwise I'd get FileNotFoundException
if I use only a file name instead of full path.
This way I can import files (e.g. another setting jsons) from other projects and it works fine.
So far so good.
However, in ASP.NET Core (I work on a Blazor Web Assembly project with ASP.NET Core backend to be more specific) when I run a server project the settings are not read from the output directory, but from the project one. Because of this I'm getting an error while trying to read a setting file from an another project in the solution, because the application looks for it in the project folder instead of the output folder.
I'm not sure if it's relevant, but Directory.GetCurrentDirectory()
shows /BlazorApp/Server
while I would rather expect /BlazorApp/Server/bin/Debug/netcoreapp3.1
.
Is this an expected behaviour in ASP.NET Core? If so, how can I work with the files from another projects? I'd like to avoid having to update settings in multiple places manually.
Thanks in advance
Upvotes: 4
Views: 6202
Reputation: 1654
To get to "/BlazorApp/Server/bin/Debug/netcoreapp3.1" you would need to use (in the System
namespace) AppDomain.CurrentDomain.BaseDirectory
You can also add another configuration file (or replace the default one) on startup as below:
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) // This is the line you would change if your configuration files were somewhere else
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("myappconfig.json", optional: false, reloadOnChange: false) // And this is the line you would add to reference a second configuration file other than appSettings.json
.Build();
BuildWebHost(args, configuration).Run();
}
public static IWebHost BuildWebHost(string[] args, IConfiguration config) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(config)
.UseStartup<Startup>()
.Build();
}`
Upvotes: 6