搜尋
首頁資料庫mysql教程.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,下面分别是例子:

  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类库的引用。

 

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
wpsystem是什么文件夹wpsystem是什么文件夹Sep 01, 2022 am 11:22 AM

wpsystem文件夹是windows应用文件夹;创建WpSystem文件夹是为了存储某些特定“Microsoft Store”应用程序的数据,因此建议不要删该文件夹,因为删除之后就无法使用指定的应用。

winreagent是什么文件夹winreagent是什么文件夹Aug 26, 2022 am 11:23 AM

winreagent是在系统更新或升级的过程中创建的文件夹;该文件夹中通常包含临时文件,当更新或升级失败时,系统将通过还原先前创建的临时文件来回滚到执行更新或升级过程之前的版本。

baidunetdiskdownload是什么文件夹baidunetdiskdownload是什么文件夹Aug 30, 2022 am 10:45 AM

baidunetdiskdownload是百度网盘默认下载文件的文件夹;百度网盘是百度推出的一项云存储服务,只要下载东西到百度网盘里,都会默认保存到这个文件夹中,并且可跨终端随时随地查看和分享。

usmt.ppkg是什么文件usmt.ppkg是什么文件Sep 09, 2022 pm 02:14 PM

“usmt.ppkg”是windows自带的系统还原功能的系统备份文件;Windows系统还原是在不需要重新安装操作系统,也不会破坏数据文件的前提下使系统回到原有的工作状态,PBR恢复功能的备份文件就是“usmt.ppkg”。

mobileemumaster是什么文件mobileemumaster是什么文件Oct 26, 2022 am 11:28 AM

mobileEmuMaster是手机模拟大师的安装文件夹。手机模拟大师是PC电脑模拟运行安卓系统的免费模拟器程序,一款可以让用户在电脑上运行手机应用的软件,支持安装安卓系统中常见的apk执行文件,支持QQ、微信等生活常用应用,达到全面兼容的效果。

kml是什么文件的格式kml是什么文件的格式Sep 14, 2022 am 10:39 AM

kml是谷歌公司创建的一种地标性文件格式;该文件用于记录某一地点或连续地点的时间、经度、纬度、海拔等地理信息数据,可以被“Google Earth”和“Google Maps”识别并显示。

备份文件的扩展名通常是什么备份文件的扩展名通常是什么Sep 01, 2022 pm 03:55 PM

备份文件的扩展名通常是“.bak”;bak文件是一个备份文件,这类文件一般在'.bak前面加上应该有原来的扩展名,有的则是由原文件的后缀名和bak混合而成,在生成了某种类型的文件后,就会自动生成它的备份文件。

config是什么文件夹可以删除吗config是什么文件夹可以删除吗Sep 13, 2022 pm 03:48 PM

config是软件或者系统中的配置文件,不可以删除;该文件是在用户开机时对计算机进行初始化设置,也就是用户对系统的设置都由它来对计算机进行恢复,因此不能删除软件或者系统中的config配置文件,以免造成错误。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器