(轉摘)c#讀寫App.config,ConfigurationManager.AppSettings 不生效


.Net開發中,我們向程序寫入一些配置信息如數據庫配置等,都是利用了App.config配置文件,本文我們來討論一下c#讀寫App.config,ConfigurationManager.AppSettings失效如何解決。

你可能知道在WinForm應用程序中可以利用Properties.Settings來進行類似的工作,但這些其實都利用了App.config配置文件。

本文探討用代碼的方式訪問 App.config 的方法。關於 App.config 的使用遠比上面提到的用途復雜,因此僅討論最基本的 appSettings 配置節。

一、配置文件概述:

應用程序配置文件是標准的 XML 文件,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置文件來更改設置,而不必重編譯應用程序。配置文件的根節點是configuration。我們經常訪問的是appSettings,它是由.Net預定義的配置節。我們經常使用的配置文件的架構是客訴下面的形式。先大概有個印象,通過后面的實例會有一個比較清楚的認識。下面的“配置節”可以理解為進行配置一個XML的節點。

常見配置文件模式:

    <configuration>
    <configSections>                //配置節聲明區域,包含配置節和命名空間聲明
    <section>                         //配置節聲明
    <sectionGroup>                //定義配置節組
    <section>                        //配置節組中的配置節聲明
    <appSettings>                   //預定義配置節
    <Custom element for configuration section>   //配置節設置區域

下面是一個最常見的應用程序配置文件的例子,只有appSettings節:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="connectionstring" value="User Source=.;Password=;Initial
Catalog=test;Provider=SQLOLEDB.1;" />
<add key="TemplatePATH" value="Template" />
</appSettings>
</configuration>

在預定義的 appSettings 節(注意大小寫),有很多的元素,這些元素名稱都是“add”,有兩個屬性分別是“key”和“value”。

.NET 提供了對appSettings節的訪問方法。在 .NET 1.0 和 1.1 版本中,可以使用 System.Configuration.ConfigurationSettings.AppSettings["Key"] 來對 key = "Key" 的<add>元素的 value屬性 進行訪問。

注意:現在.Net FrameWork 2.0中已經明確表示此ConfigurationSettings屬性已經廢棄,建議改為 ConfigurationManager 或 WebConfigurationManager。

使用 System.Configuration.ConfigurationManager,需要在工程里添加對 system.configuration.dll 程序集的引用。(在解決方案管理器中右鍵點擊工程名稱,在右鍵菜單中選擇添加引用,在.NET選項卡下即可找到。)

添加引用后,就可以用 ConfigurationManager.AppSettings["Key"] 來讀取對應的值了.

但是,ConfigurationManager.AppSettings 屬性是只讀的,並不支持修改屬性值。這是因為據說微軟不太建議我們動態寫入app.config文件,而是建議手工配置后,在程序運行時只做靜態訪問。

如果實在需要在程序中進行修改,也即寫入App.Config,請往下看。

二、appSettings配置節的讀寫操作

讀取App.config文件的appSettings節的方法比較簡單,可以通過上文中 System.Configuration.ConfigurationManager.AppSettings["Key"]的方法進行訪問,但前面也已經說了,該方法不提供寫入。

如果希望寫入配置文件,可以使用ConfigurationManager對象執行打開配置文件的操作后,將會返回一個Configuration的對象,利用該對象進行操作(增刪改查都可以哦)。

下面給出實現的代碼(增加引用using System.Configuration名稱空間)

private void AccessAppSettings()
{
//獲取Configuration對象
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//根據Key讀取<add>元素的Value
string name = config.AppSettings.Settings["name"].Value;
//寫入<add>元素的Value
config.AppSettings.Settings["name"].Value = "xieyc";
//增加<add>元素
config.AppSettings.Settings.Add("url", "http://www.xieyc.com");
//刪除<add>元素
config.AppSettings.Settings.Remove("name");
//一定要記得保存,寫不帶參數的config.Save()也可以
config.Save(ConfigurationSaveMode.Modified);
//刷新,否則程序讀取的還是之前的值(可能已裝入內存)
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}

需要注意的是:

1、根據並不存在的Key值訪問<add>元素,甚至使用remove()方法刪除不存在的元素,都不會導致異常,前者會返回null。
2、add已經存在的<add>元素也不會導致異常,而是concat了已有的Value和新的Value,用","分隔,例如:"olldvalue,newvalue"。
3、在項目進行編譯后,在運行目錄bin\Debuge文件下,將出現兩個配置文件,一個名為“ProjectName.EXE.config”,另一個名為“ProjectName.vshost.exe.config”。第一個文件為項目實際使用的配置文件,在程序運行中所做的更改都將被保存於此;第二個文件其實為原代碼中“App.config”的同步文件,在程序運行中不會發生更改。
4、特別注意大小寫(XML文件是區分大小寫的),例如appSettings配置節。
5、可能有讀者會想到,既然app.config是標准XML,當然也可以用操縱一般XML文件的方法來讀寫。這當然是可以的!具體可以看文末參考文獻[2]和[3]中的代碼,只不過我認為這樣就失去了VS提供app.config文件的意義了,還不如自己定義一個配置文件方便。

 

本文只是粗略地講了app.config文件中appSettings配置節的訪問方法,connectionStrings配置節的操作基本是類似的,也可以自定義配置節。這些高級的用法可以自己體會,VS對app.config這個配置文件的管理還是很強大的,例如WinForm應用程序的Settings設置(可以在IDE中或者通過代碼訪問)其實也是利用了app.config文件。

 

 

C#讀寫app.config中的數據詳細實例教程



讀語句:
          String str = ConfigurationManager.AppSettings["DemoKey"];

寫語句:

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

配置文件內容格式:(app.config)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
    <add key="DemoKey" value="*" />
</appSettings>
</configuration>

System.Configuration.ConfigurationSettings.AppSettings["Key"];
但是現在FrameWork2.0已經明確表示此屬性已經過時。並建議改為ConfigurationManager或WebConfigurationManager。並且AppSettings屬性是只讀的,並不支持修改屬性值.

但是要想調用ConfigurationManager必須要先在工程里添加system.configuration.dll程序集的引用。(在解決方案管理器中右鍵點擊工程名稱,在右鍵菜單中選擇添加引用,.net TablePage下即可找到)添加引用后可以用 String str = ConfigurationManager.AppSettings["Key"]來獲取對應的值了。

更新配置文件:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings.Add("key", "Name") || cfa.AppSettings.Settings["BrowseDir"].Value = "name";

最后調用
cfa.Save();
當前的配置文件更新成功。


讀寫配置文件app.config
在.Net中提供了配置文件,讓我們可以很方面的處理配置信息,這個配置是XML格式的。而且.Net中已經提供了一些訪問這個文件的功能。

1.讀取配置信息

下面是一個配置文件的具體內容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
   <add key="ConnenctionString" value="*" />
   <add key="TmpPath" value="C:\Temp" />
   </appSettings>
</configuration>

.net提供了可以直接訪問<appsettings>(注意大小寫)元素的方法,在這元素中有很多的子元素,這些子元素名稱都是“add”,有兩個屬性分別是“key”和“value”。一般情況下我們可以將自己的配置信息寫在這個區域中,通過下面的方式進行訪問:

string ConString=System.Configuration.ConfigurationSettings.AppSettings["ConnenctionString"];

在appsettings后面的是子元素的key屬性的值,例如appsettings["connenctionstring"],我們就是訪問<add key="ConnenctionString" value="*" />這個子元素,它的返回值就是“*”,即value屬性的值。

2.設置配置信息

如果配置信息是靜態的,我們可以手工配置,要注意格式。如果配置信息是動態的,就需要我們寫程序來實現。在.Net中沒有寫配置文件的功能,我們可以使用操作XML文件的方式來操作配置文件。下面就是一個寫配置文件的例子。
     

 private void SaveConfig(string ConnenctionString)
         {
             XmlDocument doc=new XmlDocument();
             //獲得配置文件的全路徑
             string strFileName=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屬性
                 XmlAttribute att=nodes[i].Attributes["key"];
                 //根據元素的第一個屬性來判斷當前的元素是不是目標元素
                 if (att.Value=="ConnectionString")
                 {
                     //對目標元素中的第二個屬性賦值
                     att=nodes[i].Attributes["value"];
                     att.Value=ConnenctionString;
                     break;
                 }
             }
             //保存上面的修改
             doc.Save(strFileName);
         }


VS2005中讀寫配置文件

VS2003中對於應用程序配置文件(app.config或者web.config)只提供了讀取的功能。而在VS2005中,對於配置文件的功能有了很大的加強。在VS2005中,對於應用程序配置文件的讀寫一般使用Configuration,ConfigurationManager兩個類。ConfigurationManager類為客戶應用程序提供了一個訪問的功能。使用ConfigurationManager對象執行打開配置文件的操作后,將會返回一個Configuration的對象。通過程序實現讀寫配置文件的代碼如下所示:

1.創建配置文件中的配置節所對應的類。該類必須繼承自ConfigurationSection
 

  public sealed class ConfigurationSections : ConfigurationSection
     {
         [ConfigurationProperty("filename", DefaultValue = "default.txt")]
         public string FileName
         {
             get
             {
                 return (string)this["filename"];
             }
             set
             {
                 this["filename"] = value;
             }
         }
     }
     public sealed class BusinessSpaceConfiguration : ConfigurationSection
     {
         [ConfigurationProperty("filename")]
         public string FileName
         {
             get
             {
                 return (string)this["filename"];
             }
             set
             {
                 this["filename"] = value;
             }
         }
     }


 

2.創建配置文件代碼
   

 private static void WriteAppConfiguration()
         {
             try
             {
                 ConfigurationSections configData = new ConfigurationSections();
                 configData.FileName = "abc.txt";
                 System.Configuration.Configuration   config =

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                 config.Sections.Remove("ConfigurationSections");
                 config.Sections.Add("ConfigurationSections", configData);
                 config.Save();

                 BusinessSpaceConfiguration bsconfigData = new BusinessSpaceConfiguration();
                 bsconfigData.FileName = "def.txt";
                 System.Configuration.Configuration config1 =

ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                 config1.Sections.Remove("BusinessSpaceConfiguration");
                 config1.Sections.Add("BusinessSpaceConfiguration", bsconfigData);
                 config1.Save();                      
             }
             catch (Exception err)
             {
                 Console.Write(err.Message);
             }
         }


 

3.生成的配置文件格式如下所示:


<?xml version="1.0" encoding="utf-8"?>
<configuration>
     <configSections>
         <section

type="ConsoleApplication1.BusinessSpaceConfiguration, ConsoleApplication1, Version=1.0.0.0,

Culture=neutral, PublicKeyToken=null" />
         <section type="ConsoleApplication1.ConfigurationSections,

ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
     </configSections>
     <BusinessSpaceConfiguration filename="def.txt" />
     <ConfigurationSections filename="abc.txt" />
</configuration>



4.讀取應用程序配置文件
    


private static void ReadAppConfiguration()
         {
             ConfigurationSections obj1 = ConfigurationManager.GetSection("ConfigurationSections")

as ConfigurationSections;
             BusinessSpaceConfiguration obj2 = ConfigurationManager.GetSection

("BusinessSpaceConfiguration") as BusinessSpaceConfiguration;
             Console.WriteLine(obj1.FileName);
             Console.WriteLine(obj2.FileName);

         }


 

自定義應用程序配置文件(app.config)

1. 配置文件概述:

應用程序配置文件是標准的 XML 文件,XML 標記和屬性是區分大小寫的。它是可以按需要更改的,開發人員可以使用配置文件來更改設置,而不必重編譯應用程序。配置文件的根節點是configuration。我們經常訪問的是appSettings,它是由.Net預定義配置節。我們經常使用的配置文件的架構是象下面的形式。先大概有個印象,通過后面的實例會有一個比較清楚的認識。下面的“配置節”可以理解為進行配置一個XML的節點。

常見配置文件模式:

<configuration>
         <configSections>                    //配置節聲明區域,包含配置節和命名空間聲明
                 <section>                   //配置節聲明
             <sectionGroup>                  //定義配置節組
                 <section>                   //配置節組中的配置節聲明
         <appSettings>                       //預定義配置節
<Custom element for configuration section>   //配置節設置區域

2.只有appSettings節的配置文件及訪問方法

下面是一個最常見的應用程序配置文件的例子,只有appSettings節。


<?xml version="1.0" encoding="utf-8"?>
<configuration>
     <appSettings>
         <add key="connectionstring" value="User Source=.;Password=;Initial
Catalog=test;Provider=SQLOLEDB.1;" />
         <add key="TemplatePATH" value="Template" />
     </appSettings>
</configuration>



下面來看看這樣的配置文件如何方法。

string _connectionString=ConfigurationSettings.AppSettings["connectionstring"];

使用ConfigurationSettings類的靜態屬性AppSettings就可以直接方法配置文件中的配置信息。這個屬性的類型是NameValueCollection。

3.自定義配置文件

3.1 自定義配置節

一個用戶自定義的配置節,在配置文件中分為兩部分:一是在<configSections></configSections>配置節中聲明配置節(上面配置文件模式中的“<section>”),另外是在<configSections></configSections >之后設置配置節(上面配置文件模式中的“<Custom element for configuration section>”),有點類似一個變量先聲明,后使用一樣。聲明一個配置文件的語句如下:
<section " type=" "/>
<section>:聲明新配置節,即可創建新配置節。

name:自定義配置節的名稱。
type:自定義配置節的類型,主要包括System.Configuration.SingleTagSectionHandler、System.Configuration.DictionarySectionHandler、System.Configuration.NameValueSectionHandler。

不同的type不但設置配置節的方式不一樣,最后訪問配置文件的操作上也有差異。下面我們就舉一個配置文件的

例子,讓它包含這三個不同的type。


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



我們對上面的自定義配置節進行說明。在聲明部分使用<section type="System.Configuration.SingleTagSectionHandler"/>聲明了一個配置節它的名字叫Test1,類型為SingleTagSectionHandler。在設置配置節部分使用 <Test1 setting1="Hello" setting2="World"/>設置了一個配置節,它的第一個設置的值是Hello,第二個值是World,當然還可以有更多。其它的兩個配置節和這個類似。
下面我們看在程序中如何訪問這些自定義的配置節。我們用過ConfigurationSettings類的靜態方法GetConfig來獲取自定義配置節的信息。

public static object GetConfig(string sectionName);

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


//訪問配置節Test1
IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("Test1");
string str = (string)IDTest1["setting1"] +" "+(string)IDTest1["setting2"];
MessageBox.Show(str);         //輸出Hello World

//訪問配置節Test1的方法2
string[] values1=new string[IDTest1.Count];
IDTest1.Values.CopyTo(values1,0);
MessageBox.Show(values1[0]+" "+values1[1]);     //輸出Hello World

//訪問配置節Test2
IDictionary 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]);

//訪問配置節Test3
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]);     //輸出Hello World
通過上面的代碼我們可以看出,不同的type通過GetConfig返回的類型不同,具體獲得配置內容的方式也不一樣。

配置節處理程序
返回類型

SingleTagSectionHandler
Systems.Collections.IDictionary

DictionarySectionHandler
Systems.Collections.IDictionary

NameValueSectionHandler
Systems.Collections.Specialized.NameValueCollection


3.2 自定義配置節組
配置節組是使用<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>
下面是訪問這個配置節組的代碼:
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]);     //輸出Hello World


配置App.config


1. 向項目添加app.config文件:

右擊項目名稱,選擇“添加”→“添加新建項”,在出現的“添加新項”對話框中,選擇“添加應用程序配置文件”;如果項目以前沒有配置文件,則默認的文件名稱為“app.config”,單擊“確定”。出現在設計器視圖中的app.config文件為:

<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
</configuration>

在項目進行編譯后,在bin\Debuge文件下,將出現兩個配置文件(以本項目為例),一個名為“JxcManagement.EXE.config”,另一個名為“JxcManagement.vshost.exe.config”。第一個文件為項目實際使用的配置文件,在程序運行中所做的更改都將被保存於此;第二個文件為原代碼“app.config”的同步文件,在程序運行中不會發生更改。

2.  connectionStrings配置節:

請注意:如果您的SQL版本為2005 Express版,則默認安裝時SQL服務器實例名為localhost\SQLExpress,須更改以下實例中“Data Source=localhost;”一句為“Data Source=localhost\SQLExpress;”,在等於號的兩邊不要加上空格。

<!--數據庫連接串-->
     <connectionStrings>
         <clear />
         <addname="conJxcBook" connectionString="Data Source=localhost;Initial Catalog=jxcbook;User                                     providerName="System.Data.SqlClient" />
     </connectionStrings>

3. appSettings配置節:

appSettings配置節為整個程序的配置,如果是對當前用戶的配置,請使用userSettings配置節,其格式與以下配置書寫要求一樣。

<!--進銷存管理系統初始化需要的參數-->
     <appSettings>
         <clear />
         <addkey="userName"value="" />
         <addkey="password"value="" />
         <addkey="Department"value="" />
         <addkey="returnValue"value="" />
         <addkey="pwdPattern"value="" />
         <addkey="userPattern"value="" />
</appSettings>

4.讀取與更新app.config

請注意:要使用以下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用。

4.1 讀取connectionStrings配置節

///<summary>
///依據連接串名字connectionName返回數據連接字符串
///</summary>
///<param ></param>
///<returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =
        ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
    Console.WriteLine(connectionString);
    return connectionString;
}

4.2 更新connectionStrings配置節

///<summary>
///更新連接字符串
///</summary>
///<param >連接字符串名稱</param>
///<param >連接字符串內容</param>
///<param >數據提供程序名稱</param>
private static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
{
    bool isModified = false;    //記錄該連接串是否已經存在
    //如果要更改的連接串已經存在
    if (ConfigurationManager.ConnectionStrings[newName] != null)
    {
        isModified = true;
    }
    //新建一個連接字符串實例
    ConnectionStringSettings mySettings =
        new ConnectionStringSettings(newName, newConString, newProviderName);
    // 打開可執行的配置文件*.exe.config
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // 如果連接串已存在,首先刪除它
    if (isModified)
    {
        config.ConnectionStrings.ConnectionStrings.Remove(newName);
    }
    // 將新的連接串添加到配置文件中.
    config.ConnectionStrings.ConnectionStrings.Add(mySettings);
    // 保存對配置文件所作的更改
    config.Save(ConfigurationSaveMode.Modified);
    // 強制重新載入配置文件的ConnectionStrings配置節
    ConfigurationManager.RefreshSection("ConnectionStrings");
}

4.3 讀取appStrings配置節

///<summary>
///返回*.exe.config文件中appSettings配置節的value項
///</summary>
///<param ></param>
///<returns></returns>
private static string GetAppConfig(string strKey)
{
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == strKey)
        {
            return ConfigurationManager.AppSettings[strKey];
        }
    }
    return null;
}

4.4 更新connectionStrings配置節

///<summary>
///在*.exe.config文件中appSettings配置節增加一對鍵、值對
///</summary>
///<param ></param>
///<param ></param>
private static void UpdateAppConfig(string newKey, string newValue)
{
    bool isModified = false;    
    foreach (string key in ConfigurationManager.AppSettings)
    {
       if(key==newKey)
        {    
            isModified = true;
        }
    }

    // Open App.Config of executable
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // You need to remove the old settings object before you can replace it
    if (isModified)
    {
        config.AppSettings.Settings.Remove(newKey);
    }    
    // Add an Application Setting.
    config.AppSettings.Settings.Add(newKey,newValue);   
    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);
    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM