Home Database Mysql Tutorial .net2.0中对config文件的操作方法总结

.net2.0中对config文件的操作方法总结

Jun 07, 2016 pm 03:00 PM
config Summarize operate document method

在.net编程中,我们经常用到config文件来保存一些常用的应用程序配置信息,在WinForm中这个文件名字是app.config,在asp.net中叫web.config。这个.config文件其实就是一个xml文件,对它的读操作微软已经提供了一个类来实现了,这个类就是System.Configuration

在.net编程中,我们经常用到config文件来保存一些常用的应用程序配置信息,在WinForm中这个文件名字是app.config,在asp.net中叫web.config。这个.config文件其实就是一个xml文件,对它的读操作微软已经提供了一个类来实现了,这个类就是System.Configuration.ConfigurationManager,下面分别是例子:

  1. //读取config里名称为“conn”数据库连接信息
  2.      connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
  3. //读取config里名称为"Font_Size"的应用程序配置信息
  4. System.Configuration.ConfigurationManager.AppSettings["Font-Size"] = 9;

不过利用这个类却不能对config文件进行写操作。对于config文件的写操作,很多人通过xml的方式来进行,按照xml的方式进行写操作在WinForm下虽然繁琐点,但是毕竟能完成。以下是按照xml文件进行写的例子。

  1. #region 保存配置
  2.             XmlDocument document = LoadXml();
  3.             XmlNode root = document.DocumentElement;
  4.             XmlNodeList nodeList = root.FirstChild.ChildNodes;
  5.             for (int i = 0; i 
  6.             {
  7.                 string key = nodeList[i].Attributes["key"].Value;
  8.                 if (key == "FilterOption")
  9.                 {
  10.                     nodeList[i].Attributes["value"].Value = ((int)container.FilterOption).ToString();
  11.                 }
  12.             }
  13.             document.Save(configPath);
  14.             #endregion


但是在WebForm下,往往会因为权限不足而报错。如下图:
.net2.0中对config文件的操作方法总结

本文提供了另外一种方式,利用.net2.0类库里面的Configuration来进行写操作。详细介绍请看下面的详细介绍。

 

Configuration 是允许进行编程访问以编辑配置文件的类。对于WebForm的config文件,可以用如下代码得到Configuration类的实例:

  1. Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);

对于WinForm的config文件,可以用如下代码得到Configuration类的实例:

 

  1. Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);

需要注意的是,对文件进行写操作之后,需要调用Save()方法保存结果。整个程序的源代码如下,并附有详细代码注释。

  1. using System;
  2. using System.Configuration;
  3. using System.Web;
  4. using System.Windows.Forms;
  5. namespace NetSkycn.Common
  6. {
  7.     /// 
  8.     /// 说明:Config文件类型枚举,
  9.    /// 分别为asp.net网站的config文件和WinForm的config文件
  10.     /// 作者:周公
  11.     /// 日期:2008-08-23
  12.     /// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
  13.     /// 
  14.     public enum ConfigType
  15.     {
  16.         /// 
  17.         /// asp.net网站的config文件
  18.         /// 
  19.         WebConfig = 1,
  20.         /// 
  21.         /// Windows应用程序的config文件
  22.         /// 
  23.         ExeConfig = 2
  24.     }
  25.     /// 
  26.     /// 说明:本类主要负责对程序配置文件(.config)进行修改的类,
  27.     /// 可以对网站和应用程序的配置文件进行修改
  28.     /// 作者:周公
  29.     /// 日期:2008-08-23
  30.     /// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
  31.     /// 
  32.     public class ConfigurationOperator
  33.     {
  34.         private Configuration config;
  35.         private string configPath;
  36.         private ConfigType configType;
  37.         /// 
  38.         /// 对应的配置文件
  39.         /// 
  40.         public Configuration Configuration
  41.         {
  42.             get { return config; }
  43.             set { config = value; }
  44.         }
  45.         /// 
  46.         /// 构造函数
  47.         /// 
  48.         /// .config文件的类型,只能是网站配置文件或者应用程序配置文件
  49.         public ConfigurationOperator(ConfigType configType)
  50.         {
  51.             this.configType = configType;
  52.             if (configType == ConfigType.ExeConfig)
  53.             {
  54.                 configPath = Application.ExecutablePath; //AppDomain.CurrentDomain.BaseDirectory;
  55.             }
  56.             else
  57.             {
  58.                 configPath = HttpContext.Current.Request.ApplicationPath;
  59.             }
  60.             Initialize();
  61.         }
  62.         /// 
  63.         /// 构造函数
  64.         /// 
  65.         /// .config文件的位置
  66.         /// .config文件的类型,只能是网站配置文件或者应用程序配置文件
  67.         public ConfigurationOperator(string configPath, ConfigType configType)
  68.         {
  69.             this.configPath = configPath;
  70.             this.configType = configType;
  71.             Initialize();
  72.         }
  73.         //实例化configuration,根据配置文件类型的不同,分别采取了不同的实例化方法
  74.         private void Initialize()
  75.         {
  76.             //如果是WinForm应用程序的配置文件
  77.             if (configType == ConfigType.ExeConfig)
  78.             {
  79.                 config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
  80.             }
  81.             else//WebForm的配置文件
  82.             {
  83.                 config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);
  84.             }
  85.         }
  86.         /// 
  87.         /// 添加应用程序配置节点,如果已经存在此节点,则会修改该节点的值
  88.         /// 
  89.         /// 节点名称
  90.         /// 节点值
  91.         public void AddAppSetting(string key, string value)
  92.         {
  93.             AppSettingsdiv appSetting = (AppSettingsdiv)config.Getdiv("appSettings");
  94.             if (appSetting.Settings[key] == null)//如果不存在此节点,则添加
  95.             {
  96.                 appSetting.Settings.Add(key, value);
  97.             }
  98.             else//如果存在此节点,则修改
  99.             {
  100.                 ModifyAppSetting(key, value);
  101.             }
  102.         }
  103.         /// 
  104.         /// 添加数据库连接字符串节点,如果已经存在此节点,则会修改该节点的值
  105.         /// 
  106.         /// 节点名称
  107.         /// 节点值
  108.         public void AddConnectionString(string key, string connectionString)
  109.         {
  110.             ConnectionStringsdiv connectionSetting = (ConnectionStringsdiv)config.Getdiv("connectionStrings");
  111.             if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加
  112.             {
  113.                 ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
  114.                 connectionSetting.ConnectionStrings.Add(connectionStringSettings);
  115.             }
  116.             else//如果存在此节点,则修改
  117.             {
  118.                 ModifyConnectionString(key, connectionString);
  119.             }
  120.         }
  121.         /// 
  122.         /// 修改应用程序配置节点,如果不存在此节点,则会添加此节点及对应的值
  123.         /// 
  124.         /// 节点名称
  125.         /// 节点值
  126.         public void ModifyAppSetting(string key, string newValue)
  127.         {
  128.             AppSettingsdiv appSetting = (AppSettingsdiv)config.Getdiv("appSettings");
  129.             if (appSetting.Settings[key] != null)//如果存在此节点,则修改
  130.             {
  131.                 appSetting.Settings[key].Value = newValue;
  132.             }
  133.             else//如果不存在此节点,则添加
  134.             {
  135.                 AddAppSetting(key, newValue);
  136.             }
  137.         }
  138.         /// 
  139.         /// 修改数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值
  140.         /// 
  141.         /// 节点名称
  142.         /// 节点值
  143.         public void ModifyConnectionString(string key, string connectionString)
  144.         {
  145.             ConnectionStringsdiv connectionSetting = (ConnectionStringsdiv)config.Getdiv("connectionStrings");
  146.             if (connectionSetting.ConnectionStrings[key] != null)//如果存在此节点,则修改
  147.             {
  148.                 connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
  149.             }
  150.             else//如果不存在此节点,则添加
  151.             {
  152.                 AddConnectionString(key, connectionString);
  153.             }
  154.         }
  155.         /// 
  156.         /// 保存所作的修改
  157.         /// 
  158.         public void Save()
  159.         {
  160.             config.Save();
  161.         }
  162.     }
  163. }

 

用法实例:
(一)WebForm中的用法

 

  1. ConfigurationOperator co = new ConfigurationOperator(ConfigType.WebConfig);
  2.         string key = txtConnectionStringKey.Text;
  3.         string value = txtConnectionStringValue.Text;
  4.         co.AddConnectionString(key, value);
  5.         co.Save();

(二)WinForm中的用法

  1. ConfigurationOperator co = new ConfigurationOperator(ConfigType.ExeConfig);
  2.             co.AddAppSetting("Font-Size""9");
  3.             co.AddAppSetting("WebSite""http://blog.csdn.net/zhoufoxcn");
  4.             co.AddConnectionString("Connection""test");
  5.             co.Save();//保存写入结果

我在WinForm里加入了一个空白的app.config文件,经过上面的操作得到如下结果(这个文件是和最后生成的exe文件在同一个目录下,而不是和源代码在同一文件夹下的那个config文件):

  1. xml version="1.0" encoding="utf-8" ?>
  2. configuration>
  3.     appSettings>
  4.         add key="Font-Size" value="9" />
  5.         add key="WebSite" value="http://blog.csdn.net/zhoufoxcn" />
  6.     appSettings>
  7.     connectionStrings>
  8.         add name="Connection" connectionString="test" />
  9.     connectionStrings>
  10. configuration>

经过这个封装类可以简化对config配置文件的操作,仅仅是需要在实例化Configuration类的实例时指明打开的是网站还是应用程序的config文件,并且在进行了所有修改和增加操作之后调用Save()方法保存所做的修改即可。需要注意的是:要想把上面的程序作为类库编译,需要添加对System.Web.dll和System.Windows.Forms.dll和System.Configuration.dll类库的引用。

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

The difference between Go language methods and functions and analysis of application scenarios The difference between Go language methods and functions and analysis of application scenarios Apr 04, 2024 am 09:24 AM

The difference between Go language methods and functions lies in their association with structures: methods are associated with structures and are used to operate structure data or methods; functions are independent of types and are used to perform general operations.

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

See all articles