hi
how to we change the web.config settings through programatically i am able to access the settings but unable to write while i save it shows access is denied error in the save
the code is
static Configuration myConfig=WebConfigurationManager.OpenWebConfiguration("~/");
static KeyValueConfigurationElement myElement = null;
myelement.value="some xyx";
myConfig.Save(); -->here it show error
myConfig.Save(ConfigurationSaveMode.Modified);
Loading
Manikavelu VelayuthamPosted Nov 25, 2010, 12:28 AM
http://www.dotnetspider.com/resources/17562-Edit-Delete-Create-Encrypt-sections.aspx
Enjoy :)
Manikavelu VelayuthamPosted Nov 25, 2010, 12:26 AM
http://stackoverflow.com/questions/1300423/how-to-edit-an-external-web-config-file
// the key of the setting
string key = "MyKey";
// the new value you want to change the setting to
string value = "This is my New Value!";
// the path to the web.config
string path = @"C:\web.config";
// open your web.config, so far this is the ONLY way i've found to do this without it wanting a virtual directory
// even "OpenExeConfiguration" will not work
var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = path }, ConfigurationUserLevel.None);
// now that we have our config, grab the element out of the settings
var element = config.AppSettings.Settings[key];
// it may be null if its not there already
if (element == null)
{
// we'll handle it not being there by adding it with the new value
config.AppSettings.Settings.Add(key, value);
}
else
{
// note: if you wanted to you could inspect the current value via element.Value
// in this case, its already present, just update the value
element.Value = value;
}
// save the config, minimal is key here if you dont want huge web.config bloat
config.Save(ConfigurationSaveMode.Minimal, true);
Before:
After:
Koteswararao MallisettiPosted Nov 25, 2010, 12:19 AM
Manikavelu VelayuthamPosted Nov 24, 2010, 12:36 AM
Sample code is also as below.
private void Form1_Load(object sender, EventArgs e)
{
XElement xml = XElement.Load(@"D:\My Tools\ModifyConfig\ModifyConfig\web.config");
var connstrxml = xml.Descendants("connectionStrings").Elements().First();
string connStr = connstrxml.Attribute("connectionString").Value;
//MessageBox.Show(connStr);
string newConnString = string.Empty;
string attribute = string.Empty;
string value = string.Empty;
string[] a = connStr.Split(';');
for (int i = 0; i < a.Length - 1; i++)
{
string[] b = a[i].Split('=');
if (b.Length == 2)
{
attribute = b[0]; value = b[1];
if (attribute.Equals("Initial Catalog", StringComparison.OrdinalIgnoreCase))
{
value = "Manik DB";
}
}
newConnString = newConnString + attribute + "=" + value + ";";
}
connstrxml.SetAttributeValue("connectionString", newConnString);
xml.Save(@"D:\My Tools\ModifyConfig\ModifyConfig\web.config");
}