3

I want to change the web.config via C#.

My Web.config

 <?xml version="1.0" encoding="utf-8"?>

    <!--
      Weitere Informationen zum Konfigurieren der ASP.NET-Anwendung finden Sie unter
      "http://go.microsoft.com/fwlink/?LinkId=169433"
      -->

    <configuration>
        <configSections>
            ...
        </configSections>
        <system.web>
            ...
        </system.web>

        <applicationSettings>
            <AdminTest.Properties.Settings>
                <setting name="AD_Admin" serializeAs="String">
                    <value>GastzugangAdmin</value>
                </setting>
                <setting name="AD_User" serializeAs="String">
                    <value>GastzugangUser</value>
                </setting>
            </AdminTest.Properties.Settings>
        </applicationSettings>
    </configuration>

With string ADAdmin = Properties.Settings.Default.AD_Admin; can I get the value from th web.config but I don't know how I can overwrite this. I try this.

protected void btnCon_Click(object sender, EventArgs e)
        {
            string con = txtCon.Text;

            try
            {
                ConfigurationManager.AppSettings.Set("AD_Admin", con);
                Settings.Default.Save();

            }
            catch (Exception)
            {

            }

        }

But I doesn't work.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Tarasov
  • 3,625
  • 19
  • 68
  • 128

1 Answers1

0

There is configuration API in .NET Fx for modifying the configuration, you can use the same. For example, check WebConfigurationManager

var config = WebConfigurationManager.OpenWebConfiguration("~/web.config");
config.AppSettings["xyz"] = value;
config.Save();

Note that your web application would be restarted whenever you save the config.

VinayC
  • 47,395
  • 5
  • 59
  • 72
  • The Acces to System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty] don't work because of securitylevel :( – Tarasov Jan 10 '13 at 13:53
  • @Tarasov, try `config.AppSettings.Settings["xyz"] = value`. BTW, the user account under which your code is running also need read/write permission on web.config file. – VinayC Jan 11 '13 at 04:34