Using appsettings.json (net 6 / 1.6.0-rc1)

1,641 views
Skip to first unread message

Andy Sprague

unread,
Sep 26, 2022, 4:33:14 PM9/26/22
to Excel-DNA
Hi,

I'm testing out the new 1.6.0-rc1 version to compile for .net core (net6.0-windows). Seems to be working very well! The only issue I'm having right now is pulling in env specific configuration after deployment. 

Do you have a suggestion on how to use the preferred ".net core" approach of appsettings.json files, instead of the .xll.config xml approach in the docs?

A code snippet (which works locally from visual studio 2022, called in AutoOpen):

```
  IConfiguration configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json")
    .Build();
```

Thanks in advance,
Andy 

Andy Sprague

unread,
Sep 26, 2022, 5:00:57 PM9/26/22
to Excel-DNA
I also tried with the following, but get the same error ( The configuration file 'appsettings.json' was not found and is not optional) :

```
var basePath = ExcelDnaUtil.XllPathInfo.Directory?.FullName ?? throw new Exception($"Unable to configure app, invalid value for ExcelDnaUtil.XllPathInfo='{ExcelDnaUtil.XllPathInfo}'");

IConfiguration configuration = new ConfigurationBuilder()
  .SetBasePath(basePath)
  .AddJsonFile("appsettings.json")
  .Build();
```

I've checked the appsettings.json file exists in the folder with the .dll file.

Andy Sprague

unread,
Sep 26, 2022, 11:06:42 PM9/26/22
to Excel-DNA
Update: The second approach actually works (using  ExcelDnaUtil.XllPathInfo ) , so this is resolved!

Oscar Peters

unread,
Oct 16, 2023, 4:26:16 PM10/16/23
to Excel-DNA
Hi,

Just want to give my two cents for when others end up here wondering how to pack the appsettings.json file in their deployable xll.
The described latter solution did seem to work for me running from VS, but when building, packing and deploying the solution, it no longer did.
After quite some searching in unknown territory and serendipitously running into AddJsonStream(), I went for embedding the appsettings.json file as an embedded resource, reading it as a stream and then using that with the help of AddJsonStream() (as part of Microsoft.Extensions.Configuration.Json package):

```
ConfigFiles files = new();
string contents   = files.File("appsettings);                           // get the file's content as a string - I had this already setup, rahter than as a stream
byte[] byteArray  = Encoding.UTF8.GetBytes(contents);    // convert to bytes
MemoryStream stream = new(byteArray);                           // convert to Stream

IConfiguration config = new ConfigurationBuilder()
.AddJsonStream(new MemoryStream(byteArray))
.Build();
```

Hope it may help anybody.


KR. Oscar

Op dinsdag 27 september 2022 om 05:06:42 UTC+2 schreef Andy Sprague:
Reply all
Reply to author
Forward
0 new messages