0

I need to change the value appSettings from the web.config file in ASP.Net through the .aspx or .cs page. Is it possible> Please provide some example, my sample code is:

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="variable" value="7" />
    <add key="logfilelocation" value="abc.txt" />
  </appSettings>
</configuration>
Bharathi
  • 1,415
  • 3
  • 15
  • 21
  • 1
    Sorry, but stackoverflow is for "what is wrong with what I have"... not "please give me working code". Have you looked at using the [inbuilt .NET XML classes](https://msdn.microsoft.com/en-us/library/system.xml%28v=vs.110%29.aspx)? – freefaller Jun 24 '15 at 10:50
  • While technically possible, there are several reasons why you should think about an alternative approach: the account that the application pool is running under should not have permissions to change the files in the web application directory. In addition, the application pool will be recycled as soon as the web.config file is written to. This will affect all of the users of the application. – Markus Jun 24 '15 at 10:54
  • read about `ConfigurationManager` class also. – Amit Kumar Ghosh Jun 24 '15 at 10:56

2 Answers2

1

Based on this thread

 Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
  myConfiguration.AppSettings.Settings.Item("myKey").Value = txtmyKey.Text;
  myConfiguration.AppSettings.Settings.Remove("MyVariable");
  myConfiguration.AppSettings.Settings.Add("MyVariable", "MyValue");
  myConfiguration.Save();
Community
  • 1
  • 1
Jagadeesh Govindaraj
  • 6,977
  • 6
  • 32
  • 52
0

Yes it's possible but should be done with caution. The example I've had to do this in is as part of an installer project, so the web.config wasn't in use and the app was being installed for the first time.

Something like this could be adapted for your purpose:

private string ConfigPath { get { return Path.Combine(targetDirectory.Substring(0, targetDirectory.LastIndexOf("\\") - 1), "Web.Config"); } }

XmlDocument doc = new XmlDocument();
doc.Load(this.ConfigPath);

XmlNode MyNode = doc.SelectSingleNode("configuration/appSettings/add[@key='YourKey']");
MyNode.Attributes["value"].Value = YourValue;

doc.Save(this.ConfigPath);

Alternatively you can use the ConfigurationManager like this to modify an existing key:

var config = System.Web.Configuration.WebConfigurationManager
      .OpenWebConfiguration("~/web.config");
config.AppSettings.Settings["Your Key"].Value = "Your Value";
config.Save(ConfigurationSaveMode.Modified);
sr28
  • 4,728
  • 5
  • 36
  • 67