Usage of ConfigurationManager
If you want to write an key to your ConfigurationManager.AppSettings, please using following code.
// Get the configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
string path = config.FilePath;
// Add an entry to appSettings.
int appStgCnt =
ConfigurationManager.AppSettings.Count;
string newKey = "NewKey" + appStgCnt.ToString();
string newValue = DateTime.Now.ToLongDateString() + " " +
DateTime.Now.ToLongTimeString();
config.AppSettings.Settings.Add(newKey, newValue);
// Save the configuration file.
//config.Save(ConfigurationSaveMode.Modified);
// Force a reload of the changed section.
ConfigurationManager.RefreshSection("appSettings");①
every thing will be ok, even that there is no configuration file. but it will not save the data to your configuration file.
if you want to save your configuration to configuration file(alway named like yourappname.exe.config),you can manual write following item to your configuration file under root node.
or you can using following code to write your configuration to configuration file.
string exePath = System.IO.Path.Combine(
Environment.CurrentDirectory, "EmbedCmdlets.exe");
// Get the configuration file.
ConfigurationManager.OpenExeConfiguration(exePath);
System.Configuration.Configuration config1 =
ConfigurationManager.OpenExeConfiguration(
exePath);
// Get the AppSetins section.
AppSettingsSection appSettingSection = config1.AppSettings;
if (null == ConfigurationManager.AppSettings["CustomPSSnapInNames"])
{
Console.WriteLine("AppSettings['CustomPSSnapInNames'] is null");
config1.AppSettings.Settings.Add("CustomPSSnapInNames", "FfsPSSnapin");
//ConfigurationManager.AppSettings.Add("CustomPSSnapInNames", "FfsPSSnapin");// read only
}
config1.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
reference:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx