在实际的项目开发中,对于项目的相关信息的配置较多,在.NET项目中,我们较多的将程序的相关配置直接存储的.config文件中,例如web.config和app.config。

.NET中配置文件分为两部分:配置的实际内容(位于appSetting节点);指定了节点的处理程序(位于configSections节点)。

在.NET程序中,.config文件存储相关配置是以xml格式,如果我们需要对配置文件进行读取和写入,以及相关节点的删除,我们可以直接采用处理xml文件的方式进行操作。也可以采用.NET提供的类System.Configuration进行相关操作。

在System.Configuration类型中,对外提供了几种方法调用,在这里介绍三种较为常用的:AppSettings,ConnectionStrings,GetSection。

接下来看一下这些方法:

1.AppSettings属性:

///<summary>///获取当前应用程序默认配置的<seecref="T:System.Configuration.AppSettingsSection"/>数据。///</summary>//////<returns>///返回一个<seecref="T:System.Collections.Specialized.NameValueCollection"/>对象,该对象包含当前应用程序默认配置的<seecref="T:System.Configuration.AppSettingsSection"/>对象的内容。///</returns>///<exceptioncref="T:System.Configuration.ConfigurationErrorsException">未能使用应用程序设置数据检索<seecref="T:System.Collections.Specialized.NameValueCollection"/>对象。</exception>publicstaticNameValueCollectionAppSettings{get;}

2.ConnectionStrings属性:

///<summary>///获取当前应用程序默认配置的<seecref="T:System.Configuration.ConnectionStringsSection"/>数据。///</summary>//////<returns>///返回一个<seecref="T:System.Configuration.ConnectionStringSettingsCollection"/>对象,该对象包含当前应用程序默认配置的<seecref="T:System.Configuration.ConnectionStringsSection"/>对象的内容。///</returns>///<exceptioncref="T:System.Configuration.ConfigurationErrorsException">未能检索<seecref="T:System.Configuration.ConnectionStringSettingsCollection"/>对象。</exception>publicstaticConnectionStringSettingsCollectionConnectionStrings{get;}

3.GetSection方法:

///<summary>///检索当前应用程序默认配置的指定配置节。///</summary>//////<returns>///指定的<seecref="T:System.Configuration.ConfigurationSection"/>对象,或者,如果该节不存在,则为null。///</returns>///<paramname="sectionName">配置节的路径和名称。</param><exceptioncref="T:System.Configuration.ConfigurationErrorsException">未能加载配置文件。</exception>publicstaticobjectGetSection(stringsectionName);

以上对几种方法进行了说明,接下来我们具体看一下在项目中对配置文件的操作:

1.获取配置值:

///<summary>///获取配置值///</summary>///<paramname="key">节点名称</param>///<returns></returns>publicstaticstringGetAppSettingValue(stringkey){if(string.IsNullOrEmpty(key)){thrownewArgumentNullException(key);}returnConfigurationManager.AppSettings[key];}

2.获取连接字符串:

///<summary>///获取连接字符串///</summary>///<paramname="name">连接字符串名称</param>///<returns></returns>publicstaticstringGetConnectionString(stringname){if(string.IsNullOrEmpty(name)){thrownewArgumentNullException(name);}returnConfigurationManager.ConnectionStrings[name].ConnectionString;}

3.获取节点的所有属性(处理单个节点):

///<summary>///获取节点的所有属性(处理单个节点)///</summary>///<paramname="name">节点名称</param>///<returns>属性的Hashtable列表</returns>publicstaticHashtableGetNodeAttribute(stringname){if(string.IsNullOrEmpty(name)){thrownewArgumentNullException(name);}return(Hashtable)ConfigurationManager.GetSection(name);}

以上的是三种获取配置文件的相关节点的操作,以下提供几种全局的写入和删除操作方法:

4.设置配置值(存在则更新,不存在则新增):

///<summary>///设置配置值(存在则更新,不存在则新增)///</summary>///<paramname="key">节点名称</param>///<paramname="value">节点值</param>publicstaticvoidSetAppSettingValue(stringkey,stringvalue){if(string.IsNullOrEmpty(key)){thrownewArgumentNullException(key);}if(string.IsNullOrEmpty(value)){thrownewArgumentNullException(value);}try{varconfig=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);varsetting=config.AppSettings.Settings[key];if(setting==null){config.AppSettings.Settings.Add(key,value);}else{setting.Value=value;}config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("appSettings");}catch(Exceptionex){thrownewException(ex.Message);}}

5.删除配置值:

///<summary>///删除配置值///</summary>///<paramname="key">节点名称</param>publicstaticvoidRemoveAppSetting(stringkey){if(string.IsNullOrEmpty(key)){thrownewArgumentNullException(key);}try{varconfig=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);config.AppSettings.Settings.Remove(key);config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("appSettings");}catch(Exceptionex){thrownewException(ex.Message);}}

6.设置连接字符串的值(存在则更新,不存在则新增):

///<summary>///设置连接字符串的值(存在则更新,不存在则新增)///</summary>///<paramname="name">名称</param>///<paramname="connstr">连接字符串</param>///<paramname="provider">程序名称属性</param>publicstaticvoidSetConnectionString(stringname,stringconnstr,stringprovider){if(string.IsNullOrEmpty(name)){thrownewArgumentNullException(name);}if(string.IsNullOrEmpty(connstr)){thrownewArgumentNullException(connstr);}if(string.IsNullOrEmpty(provider)){thrownewArgumentNullException(provider);}try{varconfig=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);varconnStrSettings=config.ConnectionStrings.ConnectionStrings[name];if(connStrSettings!=null){connStrSettings.ConnectionString=connstr;connStrSettings.ProviderName=provider;}else{connStrSettings=newConnectionStringSettings(name,connstr,provider);config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);}config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("connectionStrings");}catch(Exceptionex){thrownewException(ex.Message);}}

7.删除连接字符串配置项:

///<summary>///删除连接字符串配置项///</summary>///<paramname="name">字符串名称</param>publicstaticvoidRemoveConnectionString(stringname){if(string.IsNullOrEmpty(name)){thrownewArgumentNullException(name);}try{varconfig=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);config.ConnectionStrings.ConnectionStrings.Remove(name);config.Save(ConfigurationSaveMode.Modified);ConfigurationManager.RefreshSection("connectionStrings");}catch(Exceptionex){thrownewException(ex.Message);}}

以上的几种新增和删除操作中,如果测试过就会发现本地的.config文件中没有对应的新增节点,以及需要删除的文件节点也没有删除掉。这个原因主要是”在新增appSettings节点时,不会写入App.config或web.config中,因为AppSetting这样的节点属于内置节点,会存储在Machine.config文件中。.NET内置的处理程序定义于machine.config中,提供全局服务,无须进行任何额外工作就可以直接使用。“

如果需要对项目中的配置文件进行新增和删除操作,现在提供一种方法,采用对xml文件的操作方式:

8.更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值:

///<summary>///更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值///</summary>///<paramname="filename">配置文件的路径</param>///<paramname="key">子节点Key值</param>///<paramname="value">子节点value值</param>///<returns>返回成功与否布尔值</returns>publicstaticboolUpdateOrCreateAppSetting(stringfilename,stringkey,stringvalue){if(string.IsNullOrEmpty(filename)){thrownewArgumentNullException(filename);}if(string.IsNullOrEmpty(key)){thrownewArgumentNullException(key);}if(string.IsNullOrEmpty(value)){thrownewArgumentNullException(value);}vardoc=newXmlDocument();//加载配置文件doc.Load(filename);//得到[appSettings]节点varnode=doc.SelectSingleNode("//appSettings");try{//得到[appSettings]节点中关于Key的子节点if(node!=null){varelement=(XmlElement)node.SelectSingleNode("//add[@key='"+key+"']");if(element!=null){//存在则更新子节点Valueelement.SetAttribute("value",value);}else{//不存在则新增子节点varsubElement=doc.CreateElement("add");subElement.SetAttribute("key",key);subElement.SetAttribute("value",value);node.AppendChild(subElement);}}//保存至配置文件(方式一)using(varxmlwriter=newXmlTextWriter(filename,null)){xmlwriter.Formatting=Formatting.Indented;doc.WriteTo(xmlwriter);xmlwriter.Flush();}}catch(Exceptionex){thrownewException(ex.Message);}returntrue;}

9.更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值:

///<summary>///更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值///</summary>///<paramname="filename">配置文件路径</param>///<paramname="name">子节点name值</param>///<paramname="connectionString">子节点connectionString值</param>///<paramname="providerName">子节点providerName值</param>///<returns>返回成功与否布尔值</returns>publicstaticboolUpdateOrCreateConnectionString(stringfilename,stringname,stringconnectionString,stringproviderName){if(string.IsNullOrEmpty(filename)){thrownewArgumentNullException(filename);}if(string.IsNullOrEmpty(connectionString)){thrownewArgumentNullException(connectionString);}if(string.IsNullOrEmpty(providerName)){thrownewArgumentNullException(providerName);}vardoc=newXmlDocument();//加载配置文件doc.Load(filename);//得到[connectionStrings]节点varnode=doc.SelectSingleNode("//connectionStrings");try{//得到[connectionStrings]节点中关于Name的子节点if(node!=null){XmlElementelement=(XmlElement)node.SelectSingleNode("//add[@name='"+name+"']");if(element!=null){//存在则更新子节点element.SetAttribute("connectionString",connectionString);element.SetAttribute("providerName",providerName);}else{//不存在则新增子节点varsubElement=doc.CreateElement("add");subElement.SetAttribute("name",name);subElement.SetAttribute("connectionString",connectionString);subElement.SetAttribute("providerName",providerName);node.AppendChild(subElement);}}//保存至配置文件(方式二)doc.Save(filename);}catch(Exceptionex){thrownewException(ex.Message);}returntrue;}

10.删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值:

///<summary>///删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值///</summary>///<paramname="filename">配置文件路径</param>///<paramname="key">要删除的子节点Key值</param>///<returns>返回成功与否布尔值</returns>publicstaticboolDeleteByKey(stringfilename,stringkey){if(string.IsNullOrEmpty(filename)){thrownewArgumentNullException(filename);}if(string.IsNullOrEmpty(key)){thrownewArgumentNullException(key);}vardoc=newXmlDocument();//加载配置文件doc.Load(filename);//得到[appSettings]节点varnode=doc.SelectSingleNode("//appSettings");//得到[appSettings]节点中关于Key的子节点if(node!=null){varelement=(XmlElement)node.SelectSingleNode("//add[@key='"+key+"']");if(element!=null){//存在则删除子节点if(element.ParentNode!=null)element.ParentNode.RemoveChild(element);}}try{//保存至配置文件(方式一)using(varxmlwriter=newXmlTextWriter(filename,null)){xmlwriter.Formatting=Formatting.Indented;doc.WriteTo(xmlwriter);xmlwriter.Flush();}}catch(Exceptionex){thrownewException(ex.Message);}returntrue;}

11.删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值:

///<summary>///删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值///</summary>///<paramname="filename">配置文件路径</param>///<paramname="name">要删除的子节点name值</param>///<returns>返回成功与否布尔值</returns>publicstaticboolDeleteByName(stringfilename,stringname){if(string.IsNullOrEmpty(filename)){thrownewArgumentNullException(filename);}if(string.IsNullOrEmpty(name)){thrownewArgumentNullException(name);}vardoc=newXmlDocument();//加载配置文件doc.Load(filename);//得到[connectionStrings]节点varnode=doc.SelectSingleNode("//connectionStrings");//得到[connectionStrings]节点中关于Name的子节点if(node!=null){varelement=(XmlElement)node.SelectSingleNode("//add[@name='"+name+"']");if(element!=null){//存在则删除子节点node.RemoveChild(element);}}try{//保存至配置文件(方式二)doc.Save(filename);}catch(Exceptionex){thrownewException(ex.Message);}returntrue;}

以上对System.Configuration类的几种常用方法做了简单说明,也提供了几种较为常用的操作方法,希望对在项目中需要使用到配置文件的开发人员有用。