You need to open the configuration file before
ConfigurationManager.OpenExeConfiguration (AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
Assigns the reading to a variable and reads from it
Configuration config= ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
string campoExtra = config.AppSettings.Settings[key].Value;
MessageBox.Show(campoExtra);
I have a class that assists me in this, if it is of your interest follows below:
public static class AppConfig
{
private static Configuration config= ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
public static bool HasKey(string key)
{
return config.AppSettings.Settings.AllKeys.Contains(key);
}
public static string Get(string key)
{
return config.AppSettings.Settings[key].Value;
}
public static bool GetBolean(string key)
{
var value = config.AppSettings.Settings[key].Value;
if (string.IsNullOrEmpty(value))
return default(bool);
return bool.Parse(value);
}
public static object GetObject(string key, Type type)
{
var method = type.GetMethod("Parse");
if (method != null)
{
var v = method.Invoke(type, new[] { AppConfig.Get(key) });
return v;
}
else
{
return AppConfig.Get(key);
}
}
public static T Get<T>(string key)
{
var method = typeof(T).GetMethod("Parse", new[] { typeof(string) });
if (method != null)
{
var v = method.Invoke(typeof(T), new[] { AppConfig.Get(key) });
return (T)v;
}
throw new Exception("O tipo não é convertivel");
}
public static void SetValue(string key, object value)
{
if (value == null)
{
if (!HasKey(key))
config.AppSettings.Settings.Add(key, "");
else
config.AppSettings.Settings[key].Value = "";
}
else
{
if (!HasKey(key))
config.AppSettings.Settings.Add(key, value.ToString());
else
config.AppSettings.Settings[key].Value = value.ToString();
}
config.Save(ConfigurationSaveMode.Minimal);
}
}