0

I added a config.json file to my .NetCore 3.1 console app. project. It contains some key-value pairs, connection string etcetc.

Now When I am trying to run my app the exception being thrown in my Program.cs file is as:

The configuration file 'config.json' was not found and is not optional. The physical path is ......

I modified my .csproj file as a hopeful remedy and added following section:

<ItemGroup>
      <Content Update="config.json">
        <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      </Content>
   </ItemGroup>

The above didn't help much. Getting the same error nevertheless. I am posting a portion of code stub from Program.cs:

static void Main(string[] args)
        {
            var jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "config.json");

            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(jsonPath);

            var configuration = builder.Build(); <-- here exception
            var connectionString = configuration["connectionString"];
            .....
            .....
            .....
            .....

Any idea what it is? The json file has to be copied to its debug bin folder? I have noticed recently that I am getting a whole bunch of path read/write troubles in my .Net apps. with Visual Studio, even though the paths are just fine.

Some suggestions/advice on this please.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Prabir Choudhury
  • 143
  • 1
  • 18
  • 1
    PreserveNewest sometimes didn't work for me, I'd try to copy always. and i wouldn't change the .csproj file directly for something like this if you use VS, just use the properties window for that. (you might have to show all files in the solution explorer to be able to see the file before adding it to the project) – Patrick Beynio Mar 11 '20 at 17:18
  • "you might have to show all files in the solution explorer to be able to see the file before adding it to the project" -- do you want to see my project structure where I added it? I'm not getting you. Also, it makes no difference as such IMO whether you alter the .csproj or from properties window. Final effect is the same. What else did you use other than PreserveNewest. @PatrickBeynio – Prabir Choudhury Mar 14 '20 at 07:37

0 Answers0