How to use ConfigurationManager
Go to tools
>> nuget
>> console
and type:
Install-Package System.Configuration.ConfigurationManager
If you want a specific version:
Install-Package System.Configuration.ConfigurationManager -Version 4.5.0
Your ConfigurationManager
dll will now be imported and the code will begin to work.
Okay, it took me a while to see this, but there's no way this compiles:
return String.(ConfigurationManager.AppSettings[paramName]);
You're not even calling a method on the String
type. Just do this:
return ConfigurationManager.AppSettings[paramName];
The AppSettings
KeyValuePair already returns a string. If the name doesn't exist, it will return null
.
Based on your edit you have not yet added a Reference to the System.Configuration
assembly for the project you're working in.
I found some answers, but I don't know if it is the right way. This is my solution for now. Fortunately it didn't break my design mode.
/// <summary>
/// set config, if key is not in file, create
/// </summary>
/// <param name="key">Nome do parâmetro</param>
/// <param name="value">Valor do parâmetro</param>
public static void SetConfig(string key, string value)
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
/// <summary>
/// Get key value, if not found, return null
/// </summary>
/// <param name="key"></param>
/// <returns>null if key is not found, else string with value</returns>
public static string GetConfig(string key)
{
return ConfigurationManager.AppSettings[key];
}