app.config

 . 向項目添加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 ID=sa;password=********"
              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文件的讀寫,參照了網絡文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題爲“Read/Write App.Config File with .NET 2.0”一文。

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

4.1讀取connectionStrings配置節
///<summary>
///
依據連接串名字connectionName返回數據連接字符串
///</summary>
///<param name="connectionName"></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 name="newName">
連接字符串名稱</param>
///<param name="newConString">
連接字符串內容
</param>
///<param name="newProviderName">
數據提供程序名稱
</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 name="strKey"></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 name="newKey"></param>
///<param name="newValue"></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");
}

/// <summary>
        ///
寫入KeyValue XML文件

        /// </summary>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        public static void SaveConfig(string Key,string Value)
        {
            XmlDocument doc = new XmlDocument();
            //
獲得配置文件的全路徑
            string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "App.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 == Key)
                {
                    //
對目標元素中的第二個屬性賦值
                    att = nodes[i].Attributes["value"];
                   
                    att.Value = Value;
                    break;
                }
            }
            //
保存上面的修改
            doc.Save(strFileName);          
        }

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