1

I have:

IConfiguration cfg;
string key;

I must detect if the key exists inside cfg when the key has a 'null' value.

I know the key is inside, I see it with the debugger, but I need a method to detect that.

I thought that cfg.GetSection(key).Exists() would return True.
But it always returns False.

According to documentation, cfg.GetSection(key) never returns null, even if key doesn't exist, so it is of no help.

jps
  • 20,041
  • 15
  • 75
  • 79
codeKnight
  • 241
  • 2
  • 12
  • Didn't you ask the same [How to know if a Key exists on IConfiguration](https://stackoverflow.com/questions/61779244/how-to-know-if-a-key-exists-on-iconfiguration) already? – Pavel Anikhouski May 13 '20 at 19:28
  • I did ask - but there the answer was to use the ```Exists()``` method - but it doesn't work if the value is null – codeKnight May 13 '20 at 19:29

1 Answers1

2

Use cfg.AsEnumerable() to get the keys that are inside the configuration.
You can log and see them:

foreach (var kv in cfg.AsEnumerable()) 
{
    Console.WriteLine("{0}: {1}", kv.Key, kv.Value);
}

=> So all you need to do is just find if the specific key you are looking for is in this IEnumerable.

var keyNames = cfg.AsEnumerable().ToDictionary(x => x.Key, x => x.Value);

if (keyNames.ContainsKey(keyName))
{
    keyExistsInConfiguration = true;
}
Danielle
  • 3,324
  • 2
  • 18
  • 31