码迷,mamicode.com
首页 > Web开发 > 详细

DotNet程序配置文件

时间:2016-11-24 12:17:53      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:c#   configuration   配置文件   

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

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

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

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

  接下来看一下这些方法:

   1.AppSettings属性:

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

2.ConnectionStrings属性:

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

3.GetSection方法:

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

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

   1.获取配置值:

        /// <summary>
        /// 获取配置值
        /// </summary>
        /// <param name="key">节点名称</param>
        /// <returns></returns>
        public static string GetAppSettingValue(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(key);
            }
            return ConfigurationManager.AppSettings[key];
        }

2.获取连接字符串:

        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <returns></returns>
        public static string GetConnectionString(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(name);
            }
            return ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }

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

         /// <summary>
        /// 获取节点的所有属性(处理单个节点)
        /// </summary>
        /// <param name="name">节点名称</param>
        /// <returns>属性的Hashtable列表</returns>
        public static Hashtable GetNodeAttribute(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(name);
            }
            return (Hashtable)ConfigurationManager.GetSection(name);
        }

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

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

        /// <summary>
        /// 设置配置值(存在则更新,不存在则新增)
        /// </summary>
        /// <param name="key">节点名称</param>
        /// <param name="value">节点值</param>
        public static void SetAppSettingValue(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(key);
            }
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(value);
            }
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var setting = 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 (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

5.删除配置值:

        /// <summary>
        /// 删除配置值
        /// </summary>
        /// <param name="key">节点名称</param>
        public static void RemoveAppSetting(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(key);
            }
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings.Remove(key);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

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

        /// <summary>
        /// 设置连接字符串的值(存在则更新,不存在则新增)
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="connstr">连接字符串</param>
        /// <param name="provider">程序名称属性</param>
        public static void SetConnectionString(string name, string connstr, string provider)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(name);
            }
            if (string.IsNullOrEmpty(connstr))
            {
                throw new ArgumentNullException(connstr);
            }
            if (string.IsNullOrEmpty(provider))
            {
                throw new ArgumentNullException(provider);
            }
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var connStrSettings = config.ConnectionStrings.ConnectionStrings[name];
                if (connStrSettings != null)
                {
                    connStrSettings.ConnectionString = connstr;
                    connStrSettings.ProviderName = provider;
                }
                else
                {
                    connStrSettings = new ConnectionStringSettings(name, connstr, provider);
                    config.ConnectionStrings.ConnectionStrings.Add(connStrSettings);
                }

                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("connectionStrings");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

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

        /// <summary>
        /// 删除连接字符串配置项
        /// </summary>
        /// <param name="name">字符串名称</param>
        public static void RemoveConnectionString(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(name);
            }
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings.Remove(name);
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("connectionStrings");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

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

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

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

        /// <summary>
        /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
        /// </summary>
        /// <param name="filename">配置文件的路径</param>
        /// <param name="key">子节点Key值</param>
        /// <param name="value">子节点value值</param>
        /// <returns>返回成功与否布尔值</returns>
        public static bool UpdateOrCreateAppSetting(string filename, string key, string value)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException(filename);
            }
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(key);
            }
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(value);
            }
            var doc = new XmlDocument();
            //加载配置文件
            doc.Load(filename);
            //得到[appSettings]节点
            var node = doc.SelectSingleNode("//appSettings");
            try
            {
                //得到[appSettings]节点中关于Key的子节点
                if (node != null)
                {
                    var element = (XmlElement)node.SelectSingleNode("//add[@key=‘" + key + "‘]");
                    if (element != null)
                    {
                        //存在则更新子节点Value
                        element.SetAttribute("value", value);
                    }
                    else
                    {
                        //不存在则新增子节点
                        var subElement = doc.CreateElement("add");
                        subElement.SetAttribute("key", key);
                        subElement.SetAttribute("value", value);
                        node.AppendChild(subElement);
                    }
                }
                //保存至配置文件(方式一)
                using (var xmlwriter = new XmlTextWriter(filename, null))
                {
                    xmlwriter.Formatting = Formatting.Indented;
                    doc.WriteTo(xmlwriter);
                    xmlwriter.Flush();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return true;
        }

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

        /// <summary>
        /// 更新或新增[connectionStrings]节点的子节点值,存在则更新子节点,不存在则新增子节点,返回成功与否布尔值
        /// </summary>
        /// <param name="filename">配置文件路径</param>
        /// <param name="name">子节点name值</param>
        /// <param name="connectionString">子节点connectionString值</param>
        /// <param name="providerName">子节点providerName值</param>
        /// <returns>返回成功与否布尔值</returns>
        public static bool UpdateOrCreateConnectionString(string filename, string name, string connectionString, string providerName)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException(filename);
            }
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException(connectionString);
            }
            if (string.IsNullOrEmpty(providerName))
            {
                throw new ArgumentNullException(providerName);
            }
            var doc = new XmlDocument();
            //加载配置文件
            doc.Load(filename);
            //得到[connectionStrings]节点
            var node = doc.SelectSingleNode("//connectionStrings");
            try
            {
                //得到[connectionStrings]节点中关于Name的子节点
                if (node != null)
                {
                    XmlElement element = (XmlElement)node.SelectSingleNode("//add[@name=‘" + name + "‘]");
                    if (element != null)
                    {
                        //存在则更新子节点
                        element.SetAttribute("connectionString", connectionString);
                        element.SetAttribute("providerName", providerName);
                    }
                    else
                    {
                        //不存在则新增子节点
                        var subElement = doc.CreateElement("add");
                        subElement.SetAttribute("name", name);
                        subElement.SetAttribute("connectionString", connectionString);
                        subElement.SetAttribute("providerName", providerName);
                        node.AppendChild(subElement);
                    }
                }
                //保存至配置文件(方式二)
                doc.Save(filename);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return true;
        }

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

        /// <summary>
        /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
        /// </summary>
        /// <param name="filename">配置文件路径</param>
        /// <param name="key">要删除的子节点Key值</param>
        /// <returns>返回成功与否布尔值</returns>
        public static bool DeleteByKey(string filename, string key)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException(filename);
            }
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(key);
            }
            var doc = new XmlDocument();
            //加载配置文件
            doc.Load(filename);
            //得到[appSettings]节点
            var node = doc.SelectSingleNode("//appSettings");
            //得到[appSettings]节点中关于Key的子节点
            if (node != null)
            {
                var element = (XmlElement)node.SelectSingleNode("//add[@key=‘" + key + "‘]");
                if (element != null)
                {
                    //存在则删除子节点
                    if (element.ParentNode != null) element.ParentNode.RemoveChild(element);
                }
            }
            try
            {
                //保存至配置文件(方式一)
                using (var xmlwriter = new XmlTextWriter(filename, null))
                {
                    xmlwriter.Formatting = Formatting.Indented;
                    doc.WriteTo(xmlwriter);
                    xmlwriter.Flush();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return true;
        }

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

        /// <summary>
        /// 删除[connectionStrings]节点中包含name值的子节点,返回成功与否布尔值
        /// </summary>
        /// <param name="filename">配置文件路径</param>
        /// <param name="name">要删除的子节点name值</param>
        /// <returns>返回成功与否布尔值</returns>
        public static bool DeleteByName(string filename, string name)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException(filename);
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(name);
            }
            var doc = new XmlDocument();
            //加载配置文件
            doc.Load(filename);
            //得到[connectionStrings]节点
            var node = doc.SelectSingleNode("//connectionStrings");
            //得到[connectionStrings]节点中关于Name的子节点
            if (node != null)
            {
                var element = (XmlElement)node.SelectSingleNode("//add[@name=‘" + name + "‘]");
                if (element != null)
                {
                    //存在则删除子节点
                    node.RemoveChild(element);
                }
            }
            try
            {
                //保存至配置文件(方式二)
                doc.Save(filename);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return true;
        }

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

本文出自 “彭泽0902” 博客,请务必保留此出处http://pengze0902.blog.51cto.com/7693836/1876013

DotNet程序配置文件

标签:c#   configuration   配置文件   

原文地址:http://pengze0902.blog.51cto.com/7693836/1876013

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!