Modify the elements value in web.config at runtime

zhaozj2021-02-08  262

Everyone knows that ASP.NET provides a WebApplication configuration file web.config, allowing us to easily set up a web application, and add some units we often use in the AppSettings section, such as database connection string, etc. With the System.Configuration.configurationSetting class, we can easily read the values ​​of these units, but you need some tips to change these values. Let's tell you how to change these units with the classes in System.Management at runtime. Value.

Now you have a WebApplication name called myWebApp, the virtual path is: http: // localhost / mywebapp, directory path is: c: / inetpub / wwwroot / myWebApp, where the appSettings in the configuration file web.config is set as follows:

Create a new Console application to add the following code:

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/wwrowroot/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 ();}}} is compiled and running, Then check if myWebapp / web.config has been successfully modified! ! ! :)

转载请注明原文地址:https://www.9cbs.com/read-1179.html

New Post(0)