modifying element values in the web.config at run time Zhenyu (original)

Source: Internet
Author: User
As you all know, ASP.net provides a webapplication profile web.config that makes it easy to set up Web applications, as well as adding some of the units we often use in the appsettings section, such as database connection strings, using system.conf Iguration. Configurationsetting class We can easily read the values of these units, but to change these values will require some tricks, I will tell you how to use the System.Management in the runtime to change the values of these units.

Now suppose you have a webapplication named MyWebApp, the virtual path is: http://localhost/MyWebApp, directory path is: C:\INETPUB\WWWROOT\MYWEBAPP, The appsettings settings in the configuration file Web.config are as follows:

<configuration>
<appSettings>
<add key= "Test" value= "runtime modify Test"/>
</appSettings>

</configuration>

Create a new console application to add the following code:

Using System;
Using System.Management;

Namespace ConsoleApplication1
{
Class Class1
{
[STAThread]
static void Main (string[] args)
{
ManagementObject appset= New ManagementObject ("Root\\netframeworkv1:appsettings.directive=\ add\", key=\ "test\", Selector=\ "file://c:/inetpub/wwwroot/mywebapp/web.config\");
Console.WriteLine (String. Format ("Old value:{0}", appset["value"]);
Appset.setpropertyvalue ("Value", "new value was set ok!");
Appset.put ();
Console.WriteLine ("New value setted ok!");
Console.read ();
}
}
}

Compile and run, and then see if Mywebapp/web.config has been successfully modified


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.