C#使用WebConfigurationManager类修改Web.config文件

时间:2021-06-23 11:28:46

      在测试版2.0中有两个类:ConfigurationManager和WebConfigurationManager.ConfigurationManager不再是从网页配置文件获取设置的方法,替代它的是使用WebConfigurationManager.如果你想更新或者是添加节到文件app.config,你须使用ConfigurationManager。 

      The following is an example of how you can add an appSettings key to the web.config and also how to update an existing key: 接下来的一个例子是如何添加程序设置键值到web.config与如何更新存在的键值:

Configuration config=WebConfigurationManager.OpenWebConfiguration("~"); 
if(config.AppSettings.Settings["MyAppKey"]==null)
  config.AppSettings.Settings.Add("MyAppKey","Hello!");
else
  config.AppSettings.Settings["MyAppKey"].Value="Hello2!";
config.Save();

The WebConfigurationManager class has the following properties and methods:
WebConfigurationManager 类有以下属性和方法:
AppSettings
Gets a NameValueCollection class that has the values added to the section.
得到NameValueCollection 类以便有个值添加到节中。
ConnectionStrings
Gets a ConnectionStringSettingsCollection class that will have the connections strings added to the section.
得到个ConnectionStringSettingsCollection类,类中将有个连接字符串属性,以便添加到节中。
GetSection
With the GetSection you can get a specific section from the configuration file.
在GetSection下你能从设置文件中得到个指定的节。
GetWebApplicationSection
With the GetWebApplicationSection you can get the specified section from the web applications configuration file.
在GetWebApplicationSection下你能从网页设置文件中得到个指定的节。
Note:This method retrieves the specified configuration section from the configuration file located at the root folder of your Web application.If you want to retrieve the configuration section from the current Web application directory use the GetSection method.
注:这个方法返回定位在你网页程序root 文件中配置文件的配置节。如果你想返回当前网页程序目录下的配置节,可以使用GetSection方法。
OpenMachineConfiguration
With the OpenMachineConfiguration,you configure the machine.config file.
使用OpenMachineConfiguration,你可以配置machine.config文件。
OpenMappedMachineConfiguration
With the OpenMappedMachineConfiguration,you can open a specifed configuration file.
使用OpenMappedMachineConfiguration,你能打开个指定的配置文件。
OpenWebConfiguration
With the OpenWebConfiguration,you can open the web applications configuration file.
使用OpenWebConfiguration,你可以打开网页程序配置文件。
OpenMappedWebConfiguration
With the OpenMappedWebConfiguration,you can open a specifed web configuration file.
使用OpenmappedWebConfiguration,你可以打开指定的网页配置文件。
在ASP.NET2.0里不但进一步扩展了配置文件web.config,更为重要的是系统提供了一组API函数,让我们可以以编程的方式从配置文件里提取信息
    首先,先看看如果从web.config里提取appSettings里的配置值,示例代码如下:

< SPAN>>
  < SPAN> key="pagetitle" value="http://blog.netbei.com/Job Site Starter Kit (Ver.1.0)"></ADD< SPAN>>
  < SPAN> key="sitelogo" value="logo.gif"></ADD< SPAN>>
  < SPAN> key="advertiseemail" value="sales@somesite.com"></ADD< SPAN>>
</APPSETTINGS< SPAN>>

    利用ASP.NET2.0提供的一组API函数,您可以很容易的获取AppSettingsSection里所有的Keys/value组对,如下:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettings = (AppSettingsSection) config.GetSection("appSettings");
string[] appKeys = appSettings.Settings.AllKeys;
for (int i = 0; i < appSettings.Settings.Count; i++)
{
  //这里只进行简单的输出
  Response.Write(appSettings.Settings[appKeys[i]].Value);
  Response.Write("
");
}

     上面代码只是进行简单的输出所有Key的value值,然而,你可能想获取的仅仅是某一个key的值,这也非常简单,如下:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings")
string pateTitle= appSettings.Settings["pagetitle"].Value; //获取key为patetitle的value值
string siteLogo= appSettings.Settings["siteLogo"].Value; //获取key为sitelogo的value值

      对于数据库连接字符串,在ASP.NET2.0里提供了专门的配置节如下:

< SPAN>>
  < SPAN> name="connectionstring" connectionString="Data Source=SQLEXPRESS;AttachDbFilename=JsskDb.mdf; … .."/>
  < SPAN> name="MyProviderConnectionString" connectionString="Data Source=SQLEXPRESS;Integrated Security=True;  … …"/>
</CONNECTIONSTRINGS< SPAN>>

      这样我们很容易获取数据库连接字符串如下:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection = (ConnectionStringsSection)config.GetSection("connectionstring ");
ConnectionStringSettingsCollection conCollection = conSection.ConnectionStrings;
foreach (ConnectionStringSettings conSetting in conCollection)
{
  Response.Write(conSetting.ConnectionString);
  Response.Write("
");
}

      另外,利用API函数,你同时还可以在代码里更改web.config数据库连接的配置的值,如下

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection conSection= (ConnectionStringsSection)config.GetSection("connectionStrings");
conSection.ConnectionStrings["SQLConnectionString"].ConnectionString = "Data Source=SQLEXPRESS;Integrated Security=True;  … …";
config.Save();

      这里最有意思的可能就是类的转换,在里,使用的是AppSettingsSection类,在</ connectionStrings>里使用的的是ConnectionStringsSection类,事实上,ASP.NET2.0提供的一组函数都是“配置节名+Section”的形式提供的类。在ASP.NET官方网站曾经对此专门介绍,可以找不到该文件了。
      在ASP.NET2.0里提供了两种方式对数据库连接字符串加密,一种是使用asp_regii命令,一种是通过代码,下面显示的是通过代码方式对数据库连接字符串加密,代码如下:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configSection = config.GetSection("connectionStrings");
if (configSection.SectionInformation.IsProtected)
{//如果已经加密,就不用再加密了

  configSection.SectionInformation.UnprotectSection();
  config.Save();
}
else
{
  configSection.SectionInformation.ProtectSection ("DataProtectionConfigurationProvider");
  config.Save();
}

      这样,你检查该文件的配置可能如下:

< SPAN> configProtectionProvider="DataProtectionConfigurationProvider">
  < SPAN>>
  < SPAN>>
    < SPAN>>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAVClqG40BZkCjK40adynN8gQAAAACAAAAAAADZgAAqAAAABAAAABIhtOW …PE</CIPHERVALUE< SPAN>>
  </CIPHERDATA< SPAN>>
  </ENCRYPTEDDATA< SPAN>>
</CONNECTIONSTRINGS< SPAN>>