Writing out to a .config file.

M

Mufasa

I know in .Net 1.1 you can't write out to an app.config file but I thought
you can in 2.0.

Can somebody please post code that will show how to write to the config
file?

TIA - Jeff.
 
M

Mark Rae

Can somebody please post code that will show how to write to the config
file?

I use the following, specifically for the appSettings section:


using System.Configuration;

/// <summary>
/// Adds / updates appSettings with the specified key/value pair dictionary
/// </summary>
/// <param name="pdicSettings">Dictionary of key/value pairs</param>
/// <returns>Boolean</returns>
public static bool SaveSettings(Dictionary<string, string> pdicSettings)
{
Configuration objConfigFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

bool blnKeyExists;

foreach (KeyValuePair<string, string> kvpSetting in pdicSettings)
{
blnKeyExists = false;
foreach (string strKey in
objConfigFile.AppSettings.Settings.AllKeys)
{
if (strKey == kvpSetting.Key) // key already exists
{
blnKeyExists = true;
objConfigFile.AppSettings.Settings[kvpSetting.Key].Value =
kvpSetting.Value;
break;
}
}
if (!blnKeyExists) // key doesn't already exist, so add it
{
objConfigFile.AppSettings.Settings.Add(kvpSetting.Key,
kvpSetting.Value);
}
}

objConfigFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
 
M

Mufasa

Thanks.

J.

Mark Rae said:
Can somebody please post code that will show how to write to the config
file?

I use the following, specifically for the appSettings section:


using System.Configuration;

/// <summary>
/// Adds / updates appSettings with the specified key/value pair
dictionary
/// </summary>
/// <param name="pdicSettings">Dictionary of key/value pairs</param>
/// <returns>Boolean</returns>
public static bool SaveSettings(Dictionary<string, string> pdicSettings)
{
Configuration objConfigFile =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

bool blnKeyExists;

foreach (KeyValuePair<string, string> kvpSetting in pdicSettings)
{
blnKeyExists = false;
foreach (string strKey in
objConfigFile.AppSettings.Settings.AllKeys)
{
if (strKey == kvpSetting.Key) // key already exists
{
blnKeyExists = true;
objConfigFile.AppSettings.Settings[kvpSetting.Key].Value =
kvpSetting.Value;
break;
}
}
if (!blnKeyExists) // key doesn't already exist, so add it
{
objConfigFile.AppSettings.Settings.Add(kvpSetting.Key,
kvpSetting.Value);
}
}

objConfigFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
return true;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top