C#學習日記2017-02-14 配置文件APPconfig問題

問題描述:讀取APPconfig文件中的某個節點的的值,利用配置文件中的值初始化某些值

解決辦法:利用ConfigurationManager的Appsettings["某個要獲取的字段名"]的方法得到配置文件中的值。

  private void NormalForm_Load(object sender, EventArgs e)
        {
            string WorkUnitName = ConfigurationManager.AppSettings["WorkUnitName"].ToString().Trim(); //工位使用
            string ProcedureName = ConfigurationManager.AppSettings["ProcedureName"].ToString().Trim();//工序
            WorkUnitNO = ConfigurationManager.AppSettings["WorkUnitNO"].ToString().Trim(); //工位編碼
            ProcedureNO = ConfigurationManager.AppSettings["ProcedureNO"].ToString().Trim();//工序編碼
            tosslabOperater.Text ="    操作員:"+ OperaterName;
            tosslabStationNo.Text = "    當前工作單元: " + WorkUnitName;
            tosslabCurrentProcedure.Text = "    當前工序: " + ProcedureName;
            mShowChart();    //初次加載工位統計數目
            mShowConfig(); //判斷是否顯示配置按鈕
        }


學習內容:

1.使用ConfigurationManager對象時必須要引用System.Configuration命名空間(dll),不然會出現無法引用的錯誤,.NET中提供了System.Configuration.dll,這個命名空間下提供的類可以很方便的把這些參數配置讀寫到XML文件中。


2.一些與配置文件相關的類:

       ConfigurationManager:將當前程序的配置文件作爲Configuration對象打開。

       ConfigurationSection:表示配置文件中的區域對象。

       ConfigurationElement:表示配置文件中的元素對象。

        ConfigurationElementCollection:配置文件元素對象的集合

3.可以直接在應用程序中添加一個配置文件,點擊項目—添加類—應用程序配置文件—文件名app.config的XML文件。


4.Section區域:它是XML文件的除根節點外的一級子節點,在它的下邊還可以其他子節點和元素

Element元素:它是XML文件中的最基本的元素,它的下邊不能再有其他的元素。

這兩個元素都可以有屬性,它們的屬性就是在其XML內部的標籤。

[html] view plain copy 在CODE上查看代碼片派生到我的代碼片
<?xml version="1.0" encoding="utf-8"?>   
<configuration>  
    <configSections>  
        <section name="section1" type="OracleDataConvertTxt.AppSectionA, OracleDataConvertTxt, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
        <section name="SectionA" type="OracleDataConvertTxt.AppSectionB, OracleDataConvertTxt, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
        <section name="SectionB" type="OracleDataConvertTxt.AppSectionB, OracleDataConvertTxt, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
    </configSections>  
    <appSettings>  
        <add key="huangbo" value="1234567890" />  
    </appSettings>  
    <connectionStrings>  
        <add name="連接的名稱,就類同於Key" connectionString="具體的連接字符串" providerName="與連接字符串一起使用的提供程序的名稱。這個有時可以沒有" />  
    </connectionStrings>  
    <section1 KeyName="" KeyValue="">  
        <AppElement KeyName="this is key" KeyValue="this is value" KeyValue2="this is value2" />  
    </section1>  
    <SectionA KeyName="hahahaha" KeyValue="1234567" />  
    <SectionB KeyName="this is key name" KeyValue="this is key value">  
        <ElementCollection>  
            <add KeyName="e1 key" KeyValue="e1 value" KeyValue2="e1 value2" />  
            <add KeyName="e2 key" KeyValue="e2 value" KeyValue2="e2 value2" />  
            <add KeyName="e3 key" KeyValue="e3 value" KeyValue2="e3 value2" />  
        </ElementCollection>  
    </SectionB>  
</configuration>  

5.

一般XML文件的結構分析:

1、整個XML配置文件以<?xml version="1.0" encoding="utf-8"?> 爲頭部聲明指示版本爲1.0 字符編碼爲utf-8
2、有一個根節點<configuration>。所有內容都必須在這個根節點中。
3、有一個自定義區域的聲明塊<configSections>。所有自定義的區域必須在這個塊中聲明。
4、有二個預定義的區域<appSettings>及<connectionStrings>。它們是.NET預先定義好的區域,如果沒有使用到它們那在文件中就不會出現這二個區域。
5、若干其它自定義區域如上面出現的:<section1> ,<SectionA>, <SectionB>。這些區域的標籤名必須和自定義區域聲明中聲明的section name一致。
6、在每個自定義區域中可以有若干子節點,元素集合,與基本元素。
7、所有自定義的區域,集合,都可以有若干屬性,如<SectionA KeyName="hahahaha" KeyValue="1234567" /> 中的KeyName="hahahaha" KeyValue="1234567" 就是二個屬性。
8、所有在自定義區域下的元素都可以有若干屬性,但必須以add標識開頭,並且第一個屬性爲key值,在同一組元素中的key值不能相同。
9、二個預定義區域下的元素屬性是固定的,不可以出現除規定屬性外其它的屬性。

7.定義各個區域集合,和元素

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Configuration;  
  
namespace OracleDataConvertTxt  
{  
    //AppSectionA,AppSectionB:區域節點類,在XML中爲一個僅次於根節點的子節點。繼承自ConfigurationSection。  
    //AppElementCollection:元素集合類,在XML中爲一個區域節點下的子節點。繼承自ConfigurationElementCollection。  
    //LoadSettingsElement:元素類,在XML中爲一個基本元素。繼承自ConfigurationElement。  
    //AppSectionGroup:區域節點集合類,在XML中爲一組區域。繼承自ConfigurationSectionGroupCollection  
  
    public sealed class AppSectionA : ConfigurationSection  
    {//一個簡單的AppSectionA區域 只包含二個屬性和一個固定元素  
        //第一個屬性  
        [ConfigurationProperty("KeyName", IsRequired = true)]  
        public string KeyName  
        {  
            get { return (string)base["KeyName"]; }  
            set { base["KeyName"] = value; }  
        }  
        //第二個屬性  
        [ConfigurationProperty("KeyValue", IsRequired = true)]  
        public string KeyValue  
        {  
            get { return (string)base["KeyValue"]; }  
            set { base["KeyValue"] = value; }  
        }  
        //一個元素  
        [ConfigurationProperty("AppElement", IsRequired = true)]  
        public AppElement AppElement  
        {  
            get { return (AppElement)base["AppElement"]; }  
        }  
    }  
  
    public sealed class AppSectionB : ConfigurationSection  
    {//複雜一點AppSectionB區域,包含二個屬性和一個AcountElementCollection元素集合(元素集合的好處是可以動態的添加和刪除集合中的元素)  
        //第一個屬性  
        [ConfigurationProperty("KeyName", IsRequired = true)]  
        public string KeyName  
        {  
            get { return (string)base["KeyName"]; }  
            set { base["KeyName"] = value; }  
        }  
        //第二個屬性  
        [ConfigurationProperty("KeyValue", IsRequired = true)]  
        public string KeyValue  
        {  
            get { return (string)base["KeyValue"]; }  
            set { base["KeyValue"] = value; }  
        }  
        //一個元素  
        [ConfigurationProperty("ElementCollection", IsRequired = true)]  
        public AppElementCollection ElementCollection  
        {  
            get { return (AppElementCollection)base["ElementCollection"]; }  
        }          
    }  
  
  
    public sealed class AppElementCollection : ConfigurationElementCollection  
    {//定義一個AppElementCollection元素集合類  
  
       //其實關鍵就是這二個索引器,但它也是調用基類的實現,只是做下類型轉換就行了  
        //這二個索引器一個是字符串版本,一個是數字版本。由於這些成員被基類聲明爲了protected,所以要公開這些方法給外部使用。而索引器是不能被繼承的,所有要NEW  
        new public AppElement this[string name]  
        {  
            get { return (AppElement)base.BaseGet(name); }  
            //set 可以不用設置。因爲可以通過get返回後,直接修改返回的對象就可以了,它們是引用類型。  
            set { AppElement app = ((AppElement)BaseGet(name)); app.KeyName = value.KeyName; app.KeyValue = value.KeyValue; app.KeyValue2 = value.KeyValue2; }  
        }  
        new public AppElement this[int index]  
        {  
            get { return (AppElement)base.BaseGet(index); }  
            //set 可以不用設置。因爲可以通過get返回後,直接修改返回的對象就可以了,它們是引用類型。  
            set { AppElement app = ((AppElement)BaseGet(index)); app.KeyName = value.KeyName; app.KeyValue = value.KeyValue; app.KeyValue2 = value.KeyValue2; }  
        }  
  
        //下面二個方法中抽象類中必須要實現的  
        protected override ConfigurationElement CreateNewElement()  
        {  
            return new AppElement();              
        }  
  
        protected override object GetElementKey(ConfigurationElement element)  
        {  
            return ((AppElement)element).KeyName;  
        }  
  
        //說明:如果不需要在代碼中修改集合,可以不實現Add,Clear,Remove  
        public void Add(AppElement setting)  
        {  
            this.BaseAdd(setting);  
        }  
  
        public void Clear()  
        {  
            this.BaseClear();  
        }  
  
        public ConfigurationElement Get(string keyName)  
        {  
            return this.BaseGet(keyName);  
        }  
  
        public void Remove(string keyName)  
        {  
            this.BaseRemove(keyName);              
        }          
    }  
  
  
    public sealed class AppElement : ConfigurationElement  
    {  
        //這是定義基本的元素類,它有三個屬性,默認第一屬性爲它的Key,Key的值不能重複  
        [ConfigurationProperty("KeyName", IsRequired = true)]  
        public string KeyName  
        {  
            get { return this["KeyName"].ToString(); }  
            set { base["KeyName"] = value; }  
        }  
  
        [ConfigurationProperty("KeyValue", IsRequired = false)]  
        public string KeyValue  
        {  
            get { return this["KeyValue"].ToString(); }  
            set { this["KeyValue"] = value; }  
        }  
  
        [ConfigurationProperty("KeyValue2", IsRequired = false)]  
        public string KeyValue2  
        {  
            get { return this["KeyValue2"].ToString(); }  
            set { this["KeyValue2"] = value; }  
        }  
    }  
  
}  


8.在程序中運用:


  private void button1_Click(object sender, EventArgs e)
        {
            //得到一個配置對象  
            Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            //--------------.NET提供的二個預定義區域 AppSettings 及 ConnectionStrings -----------  

            //使用預定義的AppSettings區域配置節點,在裏面添加元素,元素必須是一個KeyValueConfigurationElement類的對象。  
            //這個對象是一個鍵、值對。  
            KeyValueConfigurationElement Element = new KeyValueConfigurationElement("huangbo", "1234567890");
            cfg.AppSettings.Settings.Add(Element);  //也可以直接寫成 cfg.AppSettings.Settings.Add("huangbo", "1234567890");              

            //使用預定義的ConnectionStrings區域配置節點,在裏面添加元素,元素必須是一個ConnectionStringSettings類的對象  
            ConnectionStringSettings constrSetting = new ConnectionStringSettings("連接的名稱,就類同於Key", "具體的連接字符串", "與連接字符串一起使用的提供程序的名稱。這個有時可以沒有");
            cfg.ConnectionStrings.ConnectionStrings.Add(constrSetting);

            //-------------以下是自定義區域------------  

            //聲明一個區域section1並把它加入到cfg中。  
            AppSectionA section1 = new AppSectionA();
            section1.AppElement.KeyName = "this is key";
            section1.AppElement.KeyValue = "this is value";
            section1.AppElement.KeyValue2 = "this is value2";
            cfg.Sections.Add("section1", section1);

            //聲明一個區域sectionA並把它加入到cfg中。  
            AppSectionB sectionA = new AppSectionB();
            sectionA.KeyName = "hahahaha";
            sectionA.KeyValue = "1234567";
            cfg.Sections.Add("SectionA", sectionA);

            //聲明一個區域sectionB並把它加入到cfg中。  
            AppSectionB sectionB = new AppSectionB();
            sectionB.KeyName = "this is key name";
            sectionB.KeyValue = "this is key value";
            AppElement e1 = new AppElement();
            AppElement e2 = new AppElement();
            AppElement e3 = new AppElement();
            e1.KeyName = "e1 key";
            e1.KeyValue = "e1 value";
            e1.KeyValue2 = "e1 value2";
            e2.KeyName = "e2 key";
            e2.KeyValue = "e2 value";
            e2.KeyValue2 = "e2 value2";
            e3.KeyName = "e3 key";
            e3.KeyValue = "e3 value";
            e3.KeyValue2 = "e3 value2";
            sectionB.ElementCollection.Add(e1);
            sectionB.ElementCollection.Add(e2);
            sectionB.ElementCollection.Add(e3);
            cfg.Sections.Add("SectionB", sectionB);

            //刪除一個元素   刪除sectionB下面ElementCollection元素集合裏的第一個Key值叫 e1 key 的元素。(Key值就是元素的第一個屬性值)  
            //必須是ElementCollection下的元素才允許被刪除,因爲ElementCollection是一個集合,集合裏的項是可以被刪除的。而直接在區域下的元素無法刪除,因爲它被定義成類的屬性了。  
            //sectionB.ElementCollection.Remove("e1 key");  

            //刪除一個區域SectionA  
            //cfg.Sections.Remove("SectionA");  

            //更新一個元素  
            //sectionB.ElementCollection["e2 key"].KeyValue = "e2 new value";  

            //將Configuration對象cfg的配置 寫入到當前XML文件中去  
            cfg.Save();

            //刷新命名節點,這樣在下次檢索它時將重新從磁盤讀取它。  
            ConfigurationManager.RefreshSection("sectionB");

            //直接給賦值  
            //AppElement tmpelement = new AppElement();  
            //tmpelement.KeyName = "bob";  
            //tmpelement.KeyValue = "bobvalue";  
            //tmpelement.KeyValue2 = "bobvalue2";  
            //AppSectionB appsection2 = cfg.GetSection("SectionB") as AppSectionB;  
            //appsection2.ElementCollection["e3 key"] = tmpelement;  
            //cfg.Save();  



        }  
        






發佈了29 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章