C#中配置文件的操作

来源:互联网 发布:照片贴图软件 编辑:程序博客网 时间:2024/05/17 21:58

注:从网上收集整理了关于C#中配置文件的资料,还加加入了自己的一些理解,希望能给大家一点帮助,如有错漏,恳请指出。

1    配置文件介绍

程序配置文件实质上是应用程序的一种针对配置信息读写最简单的工具。它重要的功能就是将命令行选项和配置文件选项统一到一种数据结构中,这样的话可以在外部设置参数,而无须修改代码来达到我们想要的效果。配合上配置文件的读写接口,操作上也较为方便。

过去常见的配置文件是以“.ini”为后缀的文本文件。INI,是英文“初始化(Initial)”的缩写。正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。格式上主要分为“节”、“参数”和“注解”三部分。后来由于Windows95推出了注册表的概念,INI配置文件在系统中的地位就大不如前了。不过作为应用程序的配置读写来说,INI还是有其牢固的地位的。

后来XML的发展也为配置文件提供了一种更好的存储格式。常见到的“config”文件扩展名的文件,也是在C#编程中较为常用的。

C#的配置文件在编码阶段,可通过添加新项找到(名为“应用程序配置文件”),添加入项目后名为app.config,程序编译后一般是以“程序名”+“.exe”+“.config”命名的文件出现。config文件的内容与配置相关的分为两大部分,一部分为应用程序的配置节(appSettings),另一部分为连接字符串的配置节(connectionStrings)。可使用C#提供的ConfigurationManager(原先使用ConfigureationSettings,现已弃用)进行读取。ConfigurationManager中比较重要的是AppSettings和ConnectionStrings两个属性,分别负责读取应用程序的配置项(appSettings)和连接字符串的配置项(connectionStrings)。如果要修改配置文件项,需要先通过ConfigurationManager的OpenExeConfigureation()方法读取信息到Configuration类中,再修改其中对应项的信息,然后执行保存,最后如果要将结果调用出来,还需要ConfigurationManager调用RefreshSection()方法进行刷新。

以上是对配置文件一些简单的介绍。下面我们来详细看一下配置文件的各种功能和用法。

 

2    INI配置文件

2.1         格式

INI配置文件以”ini”为文件扩展名,内容格式为:节、参数和注解。

每一个INI文件构成都非常类似,由若干段落(section)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键词(keyword)和一个等号,等号右边的就是关键字对应的值(value)。其一般形式如下:

[Section1]

KeyWord1 =Valuel

KeyWord2 =Value2

 ……

[Section2]

KeyWord3 =Value3

KeyWord4 =Value4

2.1.1             节

[section]

2.1.2             参数

name=value

2.1.3             注解

注解使用分号表示(;)。在分号后面的文字,直到该行结尾都全部为注解。

如:

; comment text

 

2.2         操作

C#操作INI文件使用的是Windows系统自带Win32的API函数——WritePrivateProfileString()和GetPrivateProfileString()函数。这二个函数都位于“kernel32.dll”文件中。C#中对Win32的API函数的互操作是通过命名空间“System.Runtime.InteropServices”中的“DllImport”特征类来实现的。它的主要作用是指示此属性化方法是作为非托管DLL的输出实现的。

2.2.1             读取

[ DllImport ("kernel32" ) ] 
private static extern intGetPrivateProfileString ( string section , 

string key , string def , StringBuilder retVal , 
int size , string filePath ) ; 

参数说明:sectionINI文件中的段落名称;keyINI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePathINI文件的完整路径和名称。 

2.2.2             写入

[ DllImport ( "kernel32" ) ]

private static extern longWritePrivateProfileString ( string

section ,

string key , string val , string filePath );

 

参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。

2.3 实例

下面是自行编写的一个读写INI文件的类

 

    class IniFile

    {

        //绝对路径(默认执行程序目录)

        public stringFilePath { get; set;}

 

        ///<summary>

        ///读取ini文件

        ///</summary>

        ///<param name="section">段落名</param>

        ///<param name="key"></param>

        ///<param name="defVal">缺省值</param>

        ///<param name="retVal">所对应的值,如果该key不存在则返回空值</param>

        ///<param name="size">值允许的大小</param>

        ///<param name="filePath">INI文件的完整路径和文件名</param>

        ///<returns></returns>

        [DllImport("kernel32")]

        private static extern intGetPrivateProfileString(

            string section, stringkey, string defVal,

            StringBuilder retVal,intsize,string filePath);

 

        ///<summary>

        ///写入ini文件

        ///</summary>

        ///<param name="section">段落名</param>

        ///<param name="key"></param>

        ///<param name="val"></param>

        ///<param name="filePath">INI文件的完整路径和文件名</param>

        ///<returns></returns>

        [DllImport("kernel32")]

        private static extern longWritePrivateProfileString(

            string section, stringkey, string val, stringfilePath);

 

       #region 静态方法

 

        public static string ReadVal(stringsection,string key,stringfilePath)

        {

            string defVal = "";

            StringBuilder retVal =newStringBuilder();

            int size = 10240;

            string rt = "";

            try

            {

               GetPrivateProfileString(section, key, defVal, retVal, size, filePath);

               rt = retVal.ToString();

            }

            catch

            {

               rt = "";

            }

            return rt;

        }

 

        public static bool WriteVal(stringsection,string key,stringval,string filePath)

        {

            try

            {

               if (WritePrivateProfileString(section,key, val, filePath) == 0)

                   return false;

               else

                   return true;

            }

            catch

            {

               return false;

            }

        }

 

       #endregion

 

       #region 对象方法

 

        public stringReadVal(string section, string key)

        {

            string defVal = "";

            StringBuilder retVal =newStringBuilder();

            int size = 10240;

            string rt = "";

            try

            {

               GetPrivateProfileString(section, key,

                   defVal, retVal, size, this.FilePath);

               rt = retVal.ToString();

            }

            catch

            {

               rt = "";

            }

            return rt;

        }

 

        public bool WriteVal(string section, stringkey, string val)

        {

            try

            {

               WritePrivateProfileString(section, key, val, this.FilePath);

               return true;

            }

            catch

            {

               return false;

            }

        }

 

       #endregion

    }

 

 

3    Config配置文件

3.1         文件内容层次

configuration为根节点,其下可以带有appSettings和connectionStrings两个子节点。

另外需要注意的是这两个子节点中配置项的名称和值并不一样,appSettings中为“key”和“value”,connectionStrings中为“name”和“connectionString”。

 

粗略为如下所示:

<configuration>

         <appSettings>

                   <addkey=”key1” value=”xxxx1”/>

                   <addkey=”key2” value=”xxxx2”/>

         </appSettins>

         <connctionStrings>

                   <addname=”sql1” connecitonString=”xxxx1”/>

                   <addname=”sql2” connecitonString=”xxxx2”/>

         </connectionStrings>

</configuration>

 

 

一个完整的config配置文件内容:

 

<?xmlversion="1.0"?>

<configuration>

 <startup>

   <supportedRuntimeversion="v4.0"sku=".NETFramework,Version=v4.0"/>

 </startup>

 <appSettings>

   <addkey="test1"value="test1's value is test1!"/>

   <addkey="test2"value="test2's value is test2!"/>

 </appSettings>

 <connectionStrings>

   <addname="sql1"connectionString="server=127.0.0.1; database=testdb; uid=sa; pwd=sa"/>

 </connectionStrings>

</configuration>

 

 

3.2         appSettings节的操作

config文件中appSettings的读取主要依靠ConfigurationManager类提供的两个属性:AppSettings和ConnectionStrings,通过字符串索引获取对应配置项的内容。

 

config文件中appSettings的读取主要依靠ConfigurationManager类提供的属性:AppSettings,通过字符串索引获取对应配置项的内容。

 

 

 

而写入操作,必须要先读取配置到一个特定的配置对象中,再作修改和保存。

3.2.1             读取

通过ConfigurationManager.AppSettings[key]读取

 

例子:

        public static string GetAppSetting(stringkey)

        {

            string s = "";

            try

            {

               s = ConfigurationManager.AppSettings[key];

            }

            catch { }

            return s;

        }

 

 

3.2.2             以配置对象为单位写入

写入需要将配置文件读取到Configuration对象中,然后在其中修改,最后保存。

另外注意,Configuration类是没有构造函数的,需要使用ConfigurationManager类的OpenExeConfiguration()方法打开。

 

3.2.2.1       打开

与3.3.2.1 connectionStrings的打开相同

 

1、  打开当前程序的配置文件。

Configuration config =      ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

2、  打开指定路径的配置文件。

ConfigurationManager.OpenExeConfiguration(string exePath)

 

 

3.2.2.2       修改

 

config.AppSettings.Settings[key].Value = value; //修改对应项

config.Save(ConfigurationSaveMode.Modified);//保存

ConfigurationManager.RefreshSection("appSettings");  //刷新配置文件管理类

 

 

3.2.2.3       添加

config.AppSettings.Settings.Add(key, value); //添加

//后续保存、刷新不累赘

 

3.2.2.4       删除

config.AppSettings.Settings.Remove(key); //删除

//后续保存、刷新不累赘

 

3.2.3             以配置节为单位写入

通过获取配置对象的指定节,在节上进行写入操作。

下面的修改为例(注:添加和删除也大同小异)

AppSettingsSection appSettings =(AppSettingsSection)m_Config.GetSection("appSettings");

appSettings.Settings[key].Value = value;

m_Config.Save();

 

 

3.3         connectionStrings节的操作

 

config文件中connectionStrings的读取跟appSettings类似,也要依靠ConfigurationManager类提供的属性,这个属性为ConnectionStrings。

         写入操作也类同。

 

3.3.1             读取

ConfigurationManager.ConnectionStrings[name].ConnectionString

 

3.3.2             写入

                   

 

3.3.2.1       打开

参照3.2.2.1

3.3.2.2       修改

config.ConnectionStrings.ConnectionStrings[name].ConnectionString= connectionString;

//config.ConnectionStrings.ConnectionStrings[name].ProviderName= providerName; //该项可选

 

3.3.2.3       添加

ConnectionStringSettings connSetting =newConnectionStringSettings(name, connectionString, providerName);//生成项         config.ConnectionStrings.ConnectionStrings.Add(connSetting);//添加

//后续保存、刷新

 

 

3.3.2.4       删除

                 m_Config.ConnectionStrings.ConnectionStrings.Remove(ConnectionStringSettings item); //通过指定项删除       m_Config.ConnectionStrings.ConnectionStrings.Remove(name);//通过名称删除

 

 

3.3.3             以配置节为单位写入

直接上例子:

ConnectionStringsSection connSection =(ConnectionStringsSection)m_Config.GetSection("connectionStrings");

connSection.ConnectionStrings[name].ConnectionString= connectionString;

m_Config.Save();

 

 

3.4         自定义配置节的操作

利用Configuration的GetSection()方法,获取后操作。

3.5         实例

直接上源代码:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Configuration;

 

namespace TestConfig1

{

    class ConfigMgr

    {

        ///如需要使用ConfigurationManager类还必须在引用中,引用System.Configuration

        ///ConfigurationSettings只是针对旧版的兼容(向下兼容),不建议使用

 

        ///配置文件

        privatestaticConfigurationm_Config =

            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); //读取当前程序的配置文件

   

        ///<summary>

        ///

        ///</summary>

        ///<paramname="key"></param>

        ///<returns></returns>

        public static stringGetAppSetting(string key)

        {

            strings = "";

            try

            {

                s = ConfigurationManager.AppSettings[key];

            }

            catch{ }

            returns;

        }

 

        public static stringGetConnString(string name)

        {

            strings = "";

            try

            {

                if(ConfigurationManager.ConnectionStrings[name]!=null)

                    s = ConfigurationManager.ConnectionStrings[name].ConnectionString;

            }

            catch{ }

            returns;

        }

 

        ///<summary>

        ///定义设置当前或者其他应用程序配置文件中的appSettings节点,通过AppSettings属性

        ///</summary>

        ///<paramname="key">keyName</param>

        ///<paramname="value">keyValue</param>

        public static boolSetAppSetting1(string key,string value)

        {

            try

            {

                if(m_Config.AppSettings.Settings[key] !=null)

                {

                   m_Config.AppSettings.Settings[key].Value = value;

                }

                else

                {

                   m_Config.AppSettings.Settings.Add(key, value);

                }

                m_Config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("appSettings");

                returntrue;

            }

            catch

            {

                returnfalse;

            }

        }

 

        ///<summary>

        ///定义设置当前或者其他应用程序配置文件中的appSettings节点

        ///</summary>

        ///<paramname="key">keyName</param>

        ///<paramname="value">keyValue</param>

        public static voidSetAppSetting(string key,string value)

        {

            AppSettingsSectionappSettings = (AppSettingsSection)m_Config.GetSection("appSettings");

            if(appSettings.Settings[key] !=null)

            {

                appSettings.Settings[key].Value= value;

                m_Config.Save();

            }

            else

            {

                appSettings.Settings.Add(key,value);

                m_Config.Save();

            }

            ConfigurationManager.RefreshSection("appSettings");

        }

 

        ///<summary>

        ///定义设置当前或者其他应用程序配置文件中的connectionStrings节点,通过ConnectionStrings属性

        ///</summary>

        ///<paramname="key">keyName</param>

        ///<paramname="value">keyValue</param>

        public static boolSetConnectionString1(string name,string connectionString,stringproviderName = "System.Data.SqlClient")

        {

            try

            {

                if(m_Config.ConnectionStrings.ConnectionStrings[name] !=null)

                {

                   m_Config.ConnectionStrings.ConnectionStrings[name].ConnectionString =connectionString;

                   m_Config.ConnectionStrings.ConnectionStrings[name].ProviderName =providerName;

                    //m_Config.Save(ConfigurationSaveMode.Modified);

                }

                else

                {

                    ConnectionStringSettingsconnSetting =newConnectionStringSettings(name,connectionString, providerName);

                   m_Config.ConnectionStrings.ConnectionStrings.Add(connSetting);

                    //config.Save(ConfigurationSaveMode.Modified);

                }

                m_Config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("connectionStrings");

                returntrue;

            }

            catch

            {

                returnfalse;

            }

        }

 

        ///<summary>

        ///定义设置当前或者其他应用程序配置文件中的connectionStrings节点

        ///</summary>

        ///<paramname="key">keyName</param>

        ///<paramname="value">keyValue</param>

        public static voidSetConnectionString(string name,string connectionString,stringproviderName = "System.Data.SqlClient")

        {

            //通过获取对应的节来操作实现

 

            //providerName= "System.Data.SqlClient"

            ConnectionStringsSectionconnSection = (ConnectionStringsSection)m_Config.GetSection("connectionStrings");

            if(connSection.ConnectionStrings[name] !=null)

            {

               connSection.ConnectionStrings[name].ConnectionString = connectionString;

                m_Config.Save();

            }

            else

            {

                ConnectionStringSettingsconnSettings =newConnectionStringSettings(name,connectionString, providerName);

                connSection.ConnectionStrings.Add(connSettings);

                m_Config.Save();

            }

            ConfigurationManager.RefreshSection("appSettings");

        }

 

        ///<summary>

        ///

        ///</summary>

        ///<paramname="key"></param>

        public static boolRemoveAppSetting(string key)

        {

            try

            {

                if(m_Config.AppSettings.Settings[key] !=null)

                {

                   m_Config.AppSettings.Settings.Remove(key);

                    //m_Config.Save(ConfigurationSaveMode.Modified);

                }

                m_Config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("appSettings");

                returntrue;

            }

            catch

            {

                returnfalse;

            }

        }

 

        ///<summary>

        ///

        ///</summary>

        ///<paramname="name"></param>

        public static boolRemoveConnString(string name)

        {

            try

            {

                if(m_Config.ConnectionStrings.ConnectionStrings[name] !=null)

                {

                   m_Config.ConnectionStrings.ConnectionStrings.Remove(name);

                    //m_Config.Save(ConfigurationSaveMode.Modified);

                }

                m_Config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("connectionStrings");

                returntrue;

            }

            catch

            {

                returnfalse;

            }

        }

    }

}

 

0 0
原创粉丝点击