DotNet程序配置文件

  在實際的項目開發中,對於項目的相關信息的配置較多,在.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類的幾種常用方法做了簡單說明,也提供了幾種較爲常用的操作方法,希望對在項目中需要使用到配置文件的開發人員有用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章