DotNet程序配置文件

  在實際的項目開發(fā)中,對于項目的相關信息的配置較多,在.NET項目中,我們較多的將程序的相關配置直接存儲的.config文件中,例如web.config和app.config。

創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供曲陽網(wǎng)站建設、曲陽做網(wǎng)站、曲陽網(wǎng)站設計、曲陽網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、曲陽企業(yè)網(wǎng)站模板建站服務,十余年曲陽做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。

   .NET中配置文件分為兩部分:配置的實際內(nèi)容(位于appSetting節(jié)點);指定了節(jié)點的處理程序(位于configSections節(jié)點)。

   在.NET程序中,.config文件存儲相關配置是以xml格式,如果我們需要對配置文件進行讀取和寫入,以及相關節(jié)點的刪除,我們可以直接采用處理xml文件的方式進行操作。也可以采用.NET提供的類System.Configuration進行相關操作。

  在System.Configuration類型中,對外提供了幾種方法調(diào)用,在這里介紹三種較為常用的:AppSettings,ConnectionStrings,GetSection。

  接下來看一下這些方法:

   1.AppSettings屬性:

/// <summary>
    /// 獲取當前應用程序默認配置的 <see cref="T:System.Configuration.AppSettingsSection"/> 數(shù)據(jù)。
    /// </summary>
    /// 
    /// <returns>
    /// 返回一個 <see cref="T:System.Collections.Specialized.NameValueCollection"/> 對象,該對象包含當前應用程序默認配置的 <see cref="T:System.Configuration.AppSettingsSection"/> 對象的內(nèi)容。
    /// </returns>
    /// <exception cref="T:System.Configuration.ConfigurationErrorsException">未能使用應用程序設置數(shù)據(jù)檢索 <see cref="T:System.Collections.Specialized.NameValueCollection"/> 對象。</exception>
    public static NameValueCollection AppSettings { get; }

2.ConnectionStrings屬性:

/// <summary>
    /// 獲取當前應用程序默認配置的 <see cref="T:System.Configuration.ConnectionStringsSection"/> 數(shù)據(jù)。
    /// </summary>
    /// 
    /// <returns>
    /// 返回一個 <see cref="T:System.Configuration.ConnectionStringSettingsCollection"/> 對象,該對象包含當前應用程序默認配置的 <see cref="T:System.Configuration.ConnectionStringsSection"/> 對象的內(nèi)容。
    /// </returns>
    /// <exception cref="T:System.Configuration.ConfigurationErrorsException">未能檢索 <see cref="T:System.Configuration.ConnectionStringSettingsCollection"/> 對象。</exception>
    public static ConnectionStringSettingsCollection ConnectionStrings { get; }

3.GetSection方法:

/// <summary>
    /// 檢索當前應用程序默認配置的指定配置節(jié)。
    /// </summary>
    /// 
    /// <returns>
    /// 指定的 <see cref="T:System.Configuration.ConfigurationSection"/> 對象,或者,如果該節(jié)不存在,則為 null。
    /// </returns>
    /// <param name="sectionName">配置節(jié)的路徑和名稱。</param><exception cref="T:System.Configuration.ConfigurationErrorsException">未能加載配置文件。</exception>
    public static object GetSection(string sectionName);

以上對幾種方法進行了說明,接下來我們具體看一下在項目中對配置文件的操作:

   1.獲取配置值:

        /// <summary>
        /// 獲取配置值
        /// </summary>
        /// <param name="key">節(jié)點名稱</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.獲取節(jié)點的所有屬性(處理單個節(jié)點):

         /// <summary>
        /// 獲取節(jié)點的所有屬性(處理單個節(jié)點)
        /// </summary>
        /// <param name="name">節(jié)點名稱</param>
        /// <returns>屬性的Hashtable列表</returns>
        public static Hashtable GetNodeAttribute(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(name);
            }
            return (Hashtable)ConfigurationManager.GetSection(name);
        }

  以上的是三種獲取配置文件的相關節(jié)點的操作,以下提供幾種全局的寫入和刪除操作方法:

    4.設置配置值(存在則更新,不存在則新增):

        /// <summary>
        /// 設置配置值(存在則更新,不存在則新增)
        /// </summary>
        /// <param name="key">節(jié)點名稱</param>
        /// <param name="value">節(jié)點值</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">節(jié)點名稱</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);
            }
        }

  以上的幾種新增和刪除操作中,如果測試過就會發(fā)現(xiàn)本地的.config文件中沒有對應的新增節(jié)點,以及需要刪除的文件節(jié)點也沒有刪除掉。這個原因主要是”在新增appSettings節(jié)點時,不會寫入App.config或web.config中,因為AppSetting這樣的節(jié)點屬于內(nèi)置節(jié)點,會存儲在Machine.config文件中。.NET內(nèi)置的處理程序定義于machine.config中,提供全局服務,無須進行任何額外工作就可以直接使用?!?/p>

  如果需要對項目中的配置文件進行新增和刪除操作,現(xiàn)在提供一種方法,采用對xml文件的操作方式:

     8.更新或新增[appSettings]節(jié)點的子節(jié)點值,存在則更新子節(jié)點Value,不存在則新增子節(jié)點,返回成功與否布爾值:

        /// <summary>
        /// 更新或新增[appSettings]節(jié)點的子節(jié)點值,存在則更新子節(jié)點Value,不存在則新增子節(jié)點,返回成功與否布爾值
        /// </summary>
        /// <param name="filename">配置文件的路徑</param>
        /// <param name="key">子節(jié)點Key值</param>
        /// <param name="value">子節(jié)點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]節(jié)點
            var node = doc.SelectSingleNode("http://appSettings");
            try
            {
                //得到[appSettings]節(jié)點中關于Key的子節(jié)點
                if (node != null)
                {
                    var element = (XmlElement)node.SelectSingleNode("http://add[@key='" + key + "']");
                    if (element != null)
                    {
                        //存在則更新子節(jié)點Value
                        element.SetAttribute("value", value);
                    }
                    else
                    {
                        //不存在則新增子節(jié)點
                        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]節(jié)點的子節(jié)點值,存在則更新子節(jié)點,不存在則新增子節(jié)點,返回成功與否布爾值:

        /// <summary>
        /// 更新或新增[connectionStrings]節(jié)點的子節(jié)點值,存在則更新子節(jié)點,不存在則新增子節(jié)點,返回成功與否布爾值
        /// </summary>
        /// <param name="filename">配置文件路徑</param>
        /// <param name="name">子節(jié)點name值</param>
        /// <param name="connectionString">子節(jié)點connectionString值</param>
        /// <param name="providerName">子節(jié)點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]節(jié)點
            var node = doc.SelectSingleNode("http://connectionStrings");
            try
            {
                //得到[connectionStrings]節(jié)點中關于Name的子節(jié)點
                if (node != null)
                {
                    XmlElement element = (XmlElement)node.SelectSingleNode("http://add[@name='" + name + "']");
                    if (element != null)
                    {
                        //存在則更新子節(jié)點
                        element.SetAttribute("connectionString", connectionString);
                        element.SetAttribute("providerName", providerName);
                    }
                    else
                    {
                        //不存在則新增子節(jié)點
                        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]節(jié)點中包含Key值的子節(jié)點,返回成功與否布爾值:

        /// <summary>
        /// 刪除[appSettings]節(jié)點中包含Key值的子節(jié)點,返回成功與否布爾值
        /// </summary>
        /// <param name="filename">配置文件路徑</param>
        /// <param name="key">要刪除的子節(jié)點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]節(jié)點
            var node = doc.SelectSingleNode("http://appSettings");
            //得到[appSettings]節(jié)點中關于Key的子節(jié)點
            if (node != null)
            {
                var element = (XmlElement)node.SelectSingleNode("http://add[@key='" + key + "']");
                if (element != null)
                {
                    //存在則刪除子節(jié)點
                    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]節(jié)點中包含name值的子節(jié)點,返回成功與否布爾值:

        /// <summary>
        /// 刪除[connectionStrings]節(jié)點中包含name值的子節(jié)點,返回成功與否布爾值
        /// </summary>
        /// <param name="filename">配置文件路徑</param>
        /// <param name="name">要刪除的子節(jié)點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]節(jié)點
            var node = doc.SelectSingleNode("http://connectionStrings");
            //得到[connectionStrings]節(jié)點中關于Name的子節(jié)點
            if (node != null)
            {
                var element = (XmlElement)node.SelectSingleNode("http://add[@name='" + name + "']");
                if (element != null)
                {
                    //存在則刪除子節(jié)點
                    node.RemoveChild(element);
                }
            }
            try
            {
                //保存至配置文件(方式二)
                doc.Save(filename);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return true;
        }

  以上對System.Configuration類的幾種常用方法做了簡單說明,也提供了幾種較為常用的操作方法,希望對在項目中需要使用到配置文件的開發(fā)人員有用。

網(wǎng)站欄目:DotNet程序配置文件
本文網(wǎng)址:http://muchs.cn/article24/gjgece.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設計公司、企業(yè)網(wǎng)站制作、搜索引擎優(yōu)化靜態(tài)網(wǎng)站、商城網(wǎng)站網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設