ConfigurationManager.AppSettings in Roslyn returns an empty string

663 Views Asked by At

I'm fully aware this question has been asked multiple time on here, but I have scoured the internet and have yet to find a solution.

I run the following .csx file with scriptcs (just to test and make sure the ConfigurationManager works):

#load "C:\Tickets\LoadConfig.csx"

using System;
using System.Configuration;
Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Console.WriteLine(ConfigurationManager.AppSettings.AllKeys);

Here is the LoadConfig.csx, I found it on here SO post and multiple people said they had good results.

#r "System.Configuration"

using System;
using System.IO;
using System.Linq;

var paths = new[] { Path.Combine(Environment.CurrentDirectory, "web.config"), Path.Combine(Environment.CurrentDirectory, "app.config") };
var configPath = paths.FirstOrDefault(p => File.Exists(p));

if (configPath != null)
{
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath);

    var t = typeof(System.Configuration.ConfigurationManager);
    var f = t.GetField("s_initState", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
    f.SetValue(null, 0);

    Console.Write(configPath); // Here to make sure it found the app.config file properly
}

Here's the app.config too:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>
    <appSettings>
        <add key="testKey" value="testValue" />
    </appSettings>
</configuration>

However, when I run the first code block it tells me that the current configuration file is app.config and that the AllKeys property is System.String[]. I've made sure that all the files are in the same folder and that the app.config is written correctly too. I'm just stuck right now and not sure if there are any other solutions or if I'm completely overlooking something. If anyone has any suggestions they'd be much appreciated, thanks.

1

There are 1 best solutions below

11
Bassie On

This is because you are printing ConfigurationManager.AppSettings.AllKeys directly, which is not a string so it just prints the object type.

You need to iterate around the keys with something like

var keys = ConfigurationManager.AppSettings.AllKeys;
foreach (var key in keys)
{
    Console.WriteLine(key);
}
Console.ReadLine();

or

ConfigurationManager.AppSettings.AllKeys.ToList().ForEach(k => Console.WriteLine(k));

Output:

testKey