C#各種設定檔使用,操作方法總結

來源:互聯網
上載者:User

設定檔操作

    設定檔一般分為內建配置文和使用者自訂設定檔。

    內建設定檔包括app.config、web.config、Settings.settings等等。

使用者自訂設定檔一般是將配置資訊放到XML檔案或註冊表中,配置資訊一般包括程式設定,記錄運行資訊,儲存控制項的資訊(比如位置,樣式)。

一、內建設定檔操作

app.config和web.config操作類似,以app.config為例,Settings.settings能夠指定值的類型和範圍。

1.app.config檔案操作

該設定檔中主要的節點有:connectionStrings、appSettings、configSections等,這幾個屬於常用,操作都略有不同,DotNet提供直接操作各個節點的方法。在用到ConfigurationManager時要添加system.configuration.dll程式集的引用。

程式移植後設定檔的修改會儲存在.exe.config的檔案中,但是根據我經驗如果你不修改設定檔,一般exe不自動建立一個.exe.config的檔案。

在項目進行編譯後,在bin\Debuge檔案下,將出現兩個設定檔,一個名為“*.EXE.config”,另一個名為“*.vshost.exe.config”。第一個檔案為項目實際使用的設定檔,在程式運行中所做的更改都將被儲存於此;第二個檔案為原代碼“app.config”的同步檔案,在程式運行中不會發生更改。

 

l  connectionStrings:由於儲存資料連線字串。

讀:

ConfigurationManager.ConnectionStrings["AccessDB"].ConnectionString;

寫:

//設定連接字串ConnectionStringSettings setConnStr = newConnectionStringSettings("AccessDB", connectionString,"System.Data.OleDb");//開啟當前應用程式的app.config檔案,進行操作Configuration appConfig =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);//由於沒有更新連接字串的方法,所以這裡直接再添加一個連接字串appConfig.ConnectionStrings.ConnectionStrings.Add(setConnStr);appConfig.Save();// 強制重新載入設定檔的ConnectionStrings配置節ConfigurationManager.RefreshSection("connectionStrings");

l  appSettings:主要儲存程式設定,以索引值對的形式出現。

讀:

String str = ConfigurationManager.AppSettings["DemoKey"];

寫:

Configuration cfg=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);cfg.AppSettings.Settings["DemoKey"].Value= "DemoValue";cfg.Save();

l  configSections:自訂配置節

name:自訂配置節的名稱。

type:自訂配置節的類型,主要包括:

System.Configuration.SingleTagSectionHandler

System.Configuration.DictionarySectionHandler

System.Configuration.NameValueSectionHandler。

不同的type不但設定配置節的方式不一樣,最後訪問設定檔的操作上也有差異。

三個不同的type操作:

<?xmlversion="1.0" encoding="utf-8" ?><configuration>     <configSections>         <sectiontype="System.Configuration.SingleTagSectionHandler"/>         <sectiontype="System.Configuration.DictionarySectionHandler"/>         <sectiontype="System.Configuration.NameValueSectionHandler" />     </configSections>     <Test1 setting1="Hello"setting2="World"/>     <Test2>         <add key="Hello"value="World" />     </Test2>     <Test3>         <add key="Hello"value="World" />     </Test3>   </configuration>


 

說明:在聲明部分使用<sectiontype="System.Configuration.SingleTagSectionHandler"/>聲明了一個配置節它的名字叫Test1,類型為SingleTagSectionHandler。在設定配置節部分使用 <Test1 setting1="Hello"setting2="World"/>設定了一個配置節,它的第一個設定的值是Hello,第二個值是World,當然還可以有更多。其它的兩個配置節和這個類似。 

下面我們看在程式中如何訪問這些自訂的配置節。我們用過ConfigurationSettings類的靜態方法GetConfig來擷取自訂配置節的資訊。

//訪問配置節Test1IDictionary IDTest1 =(IDictionary)ConfigurationSettings.GetConfig("Test1");string str = (string)IDTest1["setting1"]+" "+(string)IDTest1["setting2"];MessageBox.Show(str);        //輸出Hello World//訪問配置節Test1的方法2string[] values1=new string[IDTest1.Count];IDTest1.Values.CopyTo(values1,0);MessageBox.Show(values1[0]+""+values1[1]);     //輸出HelloWorld//訪問配置節Test2IDictionary IDTest2 =(IDictionary)ConfigurationSettings.GetConfig("Test2");string[] keys=new string[IDTest2.Keys.Count];string[] values=new string[IDTest2.Keys.Count];IDTest2.Keys.CopyTo(keys,0);IDTest2.Values.CopyTo(values,0);MessageBox.Show(keys[0]+" "+values[0]);//訪問配置節Test3NameValueCollectionnc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3");MessageBox.Show(nc.AllKeys[0].ToString()+""+nc["Hello"]); //輸出HelloWorld

配置節處理常式

傳回型別

SingleTagSectionHandler

Systems.Collections.IDictionary

DictionarySectionHandler

Systems.Collections.IDictionary

NameValueSectionHandler

Systems.Collections.Specialized.NameValueCollection

 

l  sectionGroup:自訂配置節組

配置節組是使用<sectionGroup>元素,將類似的配置節分到同一個組中。配置節組聲明部分將建立配置節的

包含元素,在<configSections>元素中聲明配置節組,並將屬於該組的節置於<sectionGroup>元素中。下面

是一個包含配置節組的設定檔的例子:

<?xml version="1.0"encoding="utf-8" ?><configuration>     <configSections>        <sectionGroup >            <section type="System.Configuration.NameValueSectionHandler"/>        </sectionGroup>     </configSections>       <TestGroup>        <Test>            <add key="Hello" value="World"/>        </Test>     </TestGroup></configuration>


下面是訪問這個配置節組的代碼:

NameValueCollectionnc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");

MessageBox.Show(nc.AllKeys[0].ToString()+""+nc["Hello"]);    //輸出HelloWorld

 

2.Settings.settings設定檔操作

 這個用的不多,操作也很簡單,在此不詳細敘述。

 

二、使用者自訂檔案操作

1.XML設定檔操作

XML設定檔一般由我們自己定義格式,由於某些地方對於app.config不提供寫的功能,我們就需要自己來操作這個XML,這裡我們就拿它作為例子,來說明XML的操作。

privatevoid SaveConfig(string ConnenctionString)
         {
             XmlDocument doc=new XmlDocument();
             //獲得設定檔的全路徑
             stringstrFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()+"Code.exe.config";
             doc.LOAd(strFileName);
             //找出名稱為“add”的所有元素
            XmlNodeList nodes=doc.GetElementsByTagName("add");
             for(int i=0;i<nodes.Count;i++)
             {
                 //獲得將當前元素的key屬性
                 XmlAttributeatt=nodes[i].Attributes["key"];
                 //根據元素的第一個屬性來判斷當前的元素是不是目標元素
                 if (att.Value=="ConnectionString")
                 {
                     //對目標元素中的第二個屬性賦值
                    att=nodes[i].Attributes["value"];
                    att.Value=ConnenctionString;
                     break;
                 }
             }
             //儲存上面的修改
            doc.Save(strFileName);
         }

 

2.註冊表配置操作

首先註冊表也是以索引值對的形式儲存的,DotNet提供對註冊表的操作。

操作執行個體:

      

         <span style="font-size:12px;">/// <summary>        /// 從註冊表中載入表單位置大小等資訊        /// </summary>        public static voidLoadFormPosition(System.Windows.Forms.Form Fo)        {            Microsoft.Win32.RegistryKey rk =Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\\\MapWinGISConfig",false);            try            {                if ((rk.GetValue(Fo.Name +"_x").ToString() != "") && (rk.GetValue(Fo.Name +"_y").ToString()!= "") && (rk.GetValue(Fo.Name + "_w").ToString()!= "") && (rk.GetValue(Fo.Name+ "_h").ToString() != ""))                {                    Fo.Location = newSystem.Drawing.Point(int.Parse(rk.GetValue(Fo.Name +"_x").ToString(),CultureInfo.InvariantCulture), int.Parse(rk.GetValue(Fo.Name +"_y").ToString(),CultureInfo.InvariantCulture));                    Fo.Size = newSystem.Drawing.Size(int.Parse(rk.GetValue(Fo.Name +"_w").ToString(),CultureInfo.InvariantCulture), int.Parse(rk.GetValue(Fo.Name +"_h").ToString(),CultureInfo.InvariantCulture));                }            }            catch            {            }            finally            {                rk.Close();            }        }        /// <summary>        /// 將表單位置大小資訊儲存在註冊表中       /// </summary>        public static voidSaveFormPosition(System.Windows.Forms.Form Fo)        {            Microsoft.Win32.RegistryKey rk =Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\\\\MapWinGISConfig");            if (Fo.Visible &&Fo.WindowState != System.Windows.Forms.FormWindowState.Minimized&&Fo.Location.X > -1 && Fo.Location.Y > -1 && Fo.Size.Width> 1 && Fo.Size.Height > 1)            {                rk.SetValue(Fo.Name +"_x", Fo.Location.X);                rk.SetValue(Fo.Name +"_y", Fo.Location.Y);                rk.SetValue(Fo.Name +"_w", Fo.Size.Width);                rk.SetValue(Fo.Name +"_h", Fo.Size.Height);            }            rk.Close();        }</span>

三、應用程式資訊配置

通過代碼繼承ApplicationSettingsBase類(C/S模式),在代碼中設定相關的屬性。

   1.繼承該類一般有類屬性[SettingsProvider("System.Configuration.LocalFileSettingsProvider")]-詳情如下

   2.每個屬性必須設定是[ApplicationScopedSetting()]還是[UserSocpedSetting()],還可以設定預設值[DefaultSettingValueAttribute("100,100")]

   3.屬性設定完成後,在方法層級或方法內部(視情況而定)執行個體化該繼承的類,在表單載入時設定相應屬性。載入程式配置方法有兩種-詳情如下。

   4.如果需要可以利用事件監視設定的屬性改變、儲存、載入時進行哪些操作

   5.在表單登出時儲存設定。

詳解:

 (一),LocalFileSettingsProvider---為應用程式設定類提供持久性儲存。

     1.該類提供一種機制--程式使用配置資料的機制,其將程式的設定檔案儲存到預設的位置。

     2.用戶端並不顯示訪問這個類,而是在需要服務時由設定機制自動調用,如:ApplicationSettingsBase中的很多成員都使用該類。

     3.該類將設定檔儲存為.config的XML檔案

         1.若欄位的屬性設定為[UserScopedSetting()],則儲存為user.config檔案,

           儲存位置C:\Documentsand Settings\[電腦使用者名稱]\LocalSettings\Application Data\[AssemblyCompany("huzongzhe")程式集中的一個屬性]\

         2.若欄位的屬性設定為[ApplicationScopedSetting()],則儲存為[程式名].exe.config檔案,

           儲存位置:與可執行檔相同的目錄中。

    4.ToolStripManager.LoadSettings(this)和ToolStripManager.SaveSettings(this)方法解釋

       首先,ToolStripManager提供Toolstrip相互關聯類型的一些操作,包括合并,拆分toolstrip、呈現樣式、儲存載入設定。

       其次,LoadSettings、SaveSettings的位置是C:\Documentsand Settings\[電腦使用者名稱]\LocalSettings\Application Data\[AssemblyCompany("huzongzhe")程式集中的一個屬性]\

             與LocalFileSettingsProvider提供的檔案配置是同一個位置,並且是同一個檔案。  

      最後,LoadSettings的內容:Size、IsDefault、ItemOrder、Visible、ToolStripPanelName、Name、Location等7個屬性。

 

 

 (二),載入程式配置方法

     1.通過函數Binding來綁定,這樣在程式載入時直接與設定檔的資料繫結,並且可以在值改變時直接載入到XML中。

           Binding bndBackColor = new Binding("BackColor", frmSettings1,

               "FormBackColor", true,DataSourceUpdateMode.OnPropertyChanged);

           this.DataBindings.Add(bndBackColor);

 

     2.通過提取的方法。這樣每次修改後不能動態改變,需要手動設定。

      this.Size = frmSettings1.FormSize;

 (三),[SettingsGroupName("System.Windows.Forms.ToolStripSettings.MapWinGIS.MainProgram.MapWinForm")]類屬性

     設定每個Toolstrip的首碼名,即每個組的前面限定名

     例如:tlbZoom工具條在設定檔中的標識-->System.Windows.Forms.ToolStripSettings.MapWinGIS.MainProgram.MapWinForm.tlbZoom

 

 (四),方法Reload();Reset();Save(); Upgrade();

       Reload()方法從設定檔重新載入值。

      Reset() 方法將設定重設為預設值。

       Save() 方法儲存當前設定的值。

      Upgrade()更新程式設定值。

 

程式碼範例:

 [SettingsProvider("System.Configuration.LocalFileSettingsProvider")] [SettingsGroupName("System.Windows.Forms.ToolStripSettings.MapWinGIS.MainProgram.MapWinForm")]    sealedclass ToolStripSettings : ApplicationSettingsBase    {       public ToolStripSettings(string settingsKey) : base(settingsKey)//傳過來的是toolstrip的Name屬性        {        }       [UserScopedSetting()]       public System.Drawing.Point Location        {           get            {               if (this["Location"] == null)                {                   if (this.GetPreviousVersion("Location") == null)                   {                        return newSystem.Drawing.Point(-1, -1);                   }                   return ((System.Drawing.Point)(this.GetPreviousVersion("Location")));               }               return ((System.Drawing.Point)(this["Location"]));            }          set            {               this["Location"] = value;            }        }       [UserScopedSetting(), DefaultSettingValue("StripDocker.Top")]       public string ToolStripPanelName        {           get            {               if(string.IsNullOrEmpty((string)(this["ToolStripPanelName"])))               {                   // 設定早期設定的值                    if(string.IsNullOrEmpty((string)(this.GetPreviousVersion("ToolStripPanelName"))))                   {                       // 預設值                       return string.Empty;                   }                   return ((string)(this.GetPreviousVersion("ToolStripPanelName")));               }               return ((string)(this["ToolStripPanelName"]));            }          set            {               this["ToolStripPanelName"] = value;            }        }       [UserScopedSetting()]       [DefaultSettingValue("ImageAndText")]       public string DisplayStyle        {           get            {               const string defaultValue = "ImageAndText";               if (this["DisplayStyle"] == null ||((string)(this["DisplayStyle"])) ==string.Empty)             {                   // 設定早期值                   if (this.GetPreviousVersion("DisplayStyle") == null ||((string)(this.GetPreviousVersion("DisplayStyle")))== string.Empty)                    {                        // 預設值                        return defaultValue;                   }                   return ((string)(this.GetPreviousVersion("DisplayStyle")));               }               return ((string)(this["DisplayStyle"]));            }           set            {               this["DisplayStyle"] = value;            }        }    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.