.net2.0中对config文件的操作方法总结
在.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,下面分别是例子:
- //读取config里名称为“conn”数据库连接信息
- connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
- //读取config里名称为"Font_Size"的应用程序配置信息
- System.Configuration.ConfigurationManager.AppSettings["Font-Size"] = 9;
不过利用这个类却不能对config文件进行写操作。对于config文件的写操作,很多人通过xml的方式来进行,按照xml的方式进行写操作在WinForm下虽然繁琐点,但是毕竟能完成。以下是按照xml文件进行写的例子。
- #region 保存配置
- XmlDocument document = LoadXml();
- XmlNode root = document.DocumentElement;
- XmlNodeList nodeList = root.FirstChild.ChildNodes;
- for (int i = 0; i
- {
- string key = nodeList[i].Attributes["key"].Value;
- if (key == "FilterOption")
- {
- nodeList[i].Attributes["value"].Value = ((int)container.FilterOption).ToString();
- }
- }
- document.Save(configPath);
- #endregion
但是在WebForm下,往往会因为权限不足而报错。如下图:
本文提供了另外一种方式,利用.net2.0类库里面的Configuration来进行写操作。详细介绍请看下面的详细介绍。
Configuration 是允许进行编程访问以编辑配置文件的类。对于WebForm的config文件,可以用如下代码得到Configuration类的实例:
- Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);
对于WinForm的config文件,可以用如下代码得到Configuration类的实例:
- Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
需要注意的是,对文件进行写操作之后,需要调用Save()方法保存结果。整个程序的源代码如下,并附有详细代码注释。
- using System;
- using System.Configuration;
- using System.Web;
- using System.Windows.Forms;
- namespace NetSkycn.Common
- {
-
///
- /// 说明:Config文件类型枚举,
- /// 分别为asp.net网站的config文件和WinForm的config文件
- /// 作者:周公
- /// 日期:2008-08-23
- /// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
- ///
- public enum ConfigType
- {
-
///
- /// asp.net网站的config文件
- ///
- WebConfig = 1,
-
///
- /// Windows应用程序的config文件
- ///
- ExeConfig = 2
- }
-
///
- /// 说明:本类主要负责对程序配置文件(.config)进行修改的类,
- /// 可以对网站和应用程序的配置文件进行修改
- /// 作者:周公
- /// 日期:2008-08-23
- /// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/08/24/2823508.aspx
- ///
- public class ConfigurationOperator
- {
- private Configuration config;
- private string configPath;
- private ConfigType configType;
-
///
- /// 对应的配置文件
- ///
- public Configuration Configuration
- {
- get { return config; }
- set { config = value; }
- }
-
///
- /// 构造函数
- ///
- /// .config文件的类型,只能是网站配置文件或者应用程序配置文件
- public ConfigurationOperator(ConfigType configType)
- {
- this.configType = configType;
- if (configType == ConfigType.ExeConfig)
- {
- configPath = Application.ExecutablePath; //AppDomain.CurrentDomain.BaseDirectory;
- }
- else
- {
- configPath = HttpContext.Current.Request.ApplicationPath;
- }
- Initialize();
- }
-
///
- /// 构造函数
- ///
- /// .config文件的位置
- /// .config文件的类型,只能是网站配置文件或者应用程序配置文件
- public ConfigurationOperator(string configPath, ConfigType configType)
- {
- this.configPath = configPath;
- this.configType = configType;
- Initialize();
- }
- //实例化configuration,根据配置文件类型的不同,分别采取了不同的实例化方法
- private void Initialize()
- {
- //如果是WinForm应用程序的配置文件
- if (configType == ConfigType.ExeConfig)
- {
- config = System.Configuration.ConfigurationManager.OpenExeConfiguration(configPath);
- }
- else//WebForm的配置文件
- {
- config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(configPath);
- }
- }
-
///
- /// 添加应用程序配置节点,如果已经存在此节点,则会修改该节点的值
- ///
- /// 节点名称
- /// 节点值
- public void AddAppSetting(string key, string value)
- {
- AppSettingsdiv appSetting = (AppSettingsdiv)config.Getdiv("appSettings");
- if (appSetting.Settings[key] == null)//如果不存在此节点,则添加
- {
- appSetting.Settings.Add(key, value);
- }
- else//如果存在此节点,则修改
- {
- ModifyAppSetting(key, value);
- }
- }
-
///
- /// 添加数据库连接字符串节点,如果已经存在此节点,则会修改该节点的值
- ///
- /// 节点名称
- /// 节点值
- public void AddConnectionString(string key, string connectionString)
- {
- ConnectionStringsdiv connectionSetting = (ConnectionStringsdiv)config.Getdiv("connectionStrings");
- if (connectionSetting.ConnectionStrings[key] == null)//如果不存在此节点,则添加
- {
- ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(key, connectionString);
- connectionSetting.ConnectionStrings.Add(connectionStringSettings);
- }
- else//如果存在此节点,则修改
- {
- ModifyConnectionString(key, connectionString);
- }
- }
-
///
- /// 修改应用程序配置节点,如果不存在此节点,则会添加此节点及对应的值
- ///
- /// 节点名称
- /// 节点值
- public void ModifyAppSetting(string key, string newValue)
- {
- AppSettingsdiv appSetting = (AppSettingsdiv)config.Getdiv("appSettings");
- if (appSetting.Settings[key] != null)//如果存在此节点,则修改
- {
- appSetting.Settings[key].Value = newValue;
- }
- else//如果不存在此节点,则添加
- {
- AddAppSetting(key, newValue);
- }
- }
-
///
- /// 修改数据库连接字符串节点,如果不存在此节点,则会添加此节点及对应的值
- ///
- /// 节点名称
- /// 节点值
- public void ModifyConnectionString(string key, string connectionString)
- {
- ConnectionStringsdiv connectionSetting = (ConnectionStringsdiv)config.Getdiv("connectionStrings");
- if (connectionSetting.ConnectionStrings[key] != null)//如果存在此节点,则修改
- {
- connectionSetting.ConnectionStrings[key].ConnectionString = connectionString;
- }
- else//如果不存在此节点,则添加
- {
- AddConnectionString(key, connectionString);
- }
- }
-
///
- /// 保存所作的修改
- ///
- public void Save()
- {
- config.Save();
- }
- }
- }
用法实例:
(一)WebForm中的用法
- ConfigurationOperator co = new ConfigurationOperator(ConfigType.WebConfig);
- string key = txtConnectionStringKey.Text;
- string value = txtConnectionStringValue.Text;
- co.AddConnectionString(key, value);
- co.Save();
(二)WinForm中的用法
- ConfigurationOperator co = new ConfigurationOperator(ConfigType.ExeConfig);
- co.AddAppSetting("Font-Size", "9");
- co.AddAppSetting("WebSite", "http://blog.csdn.net/zhoufoxcn");
- co.AddConnectionString("Connection", "test");
- co.Save();//保存写入结果
我在WinForm里加入了一个空白的app.config文件,经过上面的操作得到如下结果(这个文件是和最后生成的exe文件在同一个目录下,而不是和源代码在同一文件夹下的那个config文件):
- xml version="1.0" encoding="utf-8" ?>
- configuration>
- appSettings>
- add key="Font-Size" value="9" />
- add key="WebSite" value="http://blog.csdn.net/zhoufoxcn" />
- appSettings>
- connectionStrings>
- add name="Connection" connectionString="test" />
- connectionStrings>
- configuration>
经过这个封装类可以简化对config配置文件的操作,仅仅是需要在实例化Configuration类的实例时指明打开的是网站还是应用程序的config文件,并且在进行了所有修改和增加操作之后调用Save()方法保存所做的修改即可。需要注意的是:要想把上面的程序作为类库编译,需要添加对System.Web.dll和System.Windows.Forms.dll和System.Configuration.dll类库的引用。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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.

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

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

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

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 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.

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:
