.NET配置文件讀寫實例(附SosoftConfigHelper類)


配置文件在軟件開發中起到舉足輕重的作用,可以說不可或缺。.NET程序可使用.config文件作為配置文件,例如WinForm程序的*.app.config、Web程序的web.config。.config文件是標准的XML文件。本實例可讀取、修改和添加app.confing或者web.config文件的appSettings。SosoftConfigHelper類還可以讀寫ConnectionStrings。

使用Visual Studio創建一個WinForm項目,在窗體上建立控件,如圖:

鍵值列表中的值是運行結果。

然后在更新配置按鈕事件方法中加入如下代碼:

SosoftConfigHelper.UpdateAppConfig(textBox_key.Text, textBox_value.Text);

窗體的代碼如下:

/*
Copyright (c) 2012  柔城  All rights reserved.
 * 
 * sosoft.cnblogs.com
 */
using System;
using System.Configuration;
using System.Windows.Forms;
using Sosoft.Cnblogs.Com.Helper;

namespace Sosoft.Cnblogs.Com
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void button_update_Click(object sender, EventArgs e)
        {
            SosoftConfigHelper.UpdateAppConfig(textBox_key.Text, textBox_value.Text);
            GetKeyValueList();
        }

        private void GetKeyValueList()
        {
            textBox_keyValueList.Text = string.Empty;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                textBox_keyValueList.Text += key + " : " + SosoftConfigHelper.GetAppConfig(key) + "\r\n";
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            GetKeyValueList();
        }
    }
}

記得要添加System.Configuration命名空間和程序集的引用。

另外新建一個類,命名SosoftConfigHelper.cs,這是配置文件讀寫類,代碼如下:

  1 /*
  2 Copyright (c) 2012  柔城  All rights reserved.
  3  * 
  4  * sosoft.cnblogs.com
  5  */
  6 using System;
  7 using System.Configuration;
  8 
  9 namespace Sosoft.Cnblogs.Com.Helper
 10 {
 11     /// <summary>
 12     /// Sosoft配置文件輔助類
 13     /// </summary>
 14     public class SosoftConfigHelper
 15     {
 16         /// <summary>
 17         ///  讀取appStrings配置節, 返回*.exe.config文件中appSettings配置節的value項
 18         /// </summary>
 19         /// <param name="strKey"></param>
 20         /// <returns></returns>
 21         public static string GetAppConfig(string strKey)
 22         {
 23             foreach (string key in ConfigurationManager.AppSettings)
 24             {
 25                 if (key == strKey)
 26                 {
 27                     return ConfigurationManager.AppSettings[strKey];
 28                 }
 29             }
 30             return null;
 31         }
 32 
 33 
 34         /// <summary>
 35         /// 更新appStrings配置節,在*.exe.config文件中appSettings配置節增加一對鍵、值對
 36         /// </summary>
 37         /// <param name="newKey"></param>
 38         /// <param name="newValue"></param>
 39         public static void UpdateAppConfig(string newKey, string newValue)
 40         {
 41             bool isModified = false;
 42             foreach (string key in ConfigurationManager.AppSettings)
 43             {
 44                 if (key == newKey)
 45                 {
 46                     isModified = true;
 47                 }
 48             }
 49 
 50             // Open App.Config of executable
 51             Configuration config =
 52                 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
 53             // You need to remove the old settings object before you can replace it
 54             if (isModified)
 55             {
 56                 config.AppSettings.Settings.Remove(newKey);
 57             }
 58             // Add an Application Setting.
 59             config.AppSettings.Settings.Add(newKey, newValue);
 60             // Save the changes in App.config file.
 61             config.Save(ConfigurationSaveMode.Modified);
 62             // Force a reload of a changed section.
 63             ConfigurationManager.RefreshSection("appSettings");
 64         }
 65 
 66 
 67 
 68         /// <summary>
 69         /// 讀取connectionStrings配置節,依據連接串名字connectionName返回數據連接字符串
 70         /// </summary>
 71         /// <param name="connectionName"></param>
 72         /// <returns></returns>
 73         public static string GetConnectionStringsConfig(string connectionName)
 74         {
 75             string connectionString =
 76                     ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
 77             Console.WriteLine(connectionString);
 78             return connectionString;
 79         }
 80 
 81 
 82         /// <summary>
 83         /// 更新connectionStrings配置節, 更新連接字符串
 84         /// </summary>
 85         /// <param name="newName"> 連接字符串名稱 </param>
 86         /// <param name="newConString"> 連接字符串內容 </param>
 87         /// <param name="newProviderName"> 數據提供程序名稱 </param>
 88         public static void UpdateConnectionStringsConfig(string newName,
 89             string newConString,
 90             string newProviderName)
 91         {
 92             bool isModified = false;    // 記錄該連接串是否已經存在
 93             // 如果要更改的連接串已經存在
 94             if (ConfigurationManager.ConnectionStrings[newName] != null)
 95             {
 96                 isModified = true;
 97             }
 98             // 新建一個連接字符串實例
 99             ConnectionStringSettings mySettings =
100                 new ConnectionStringSettings(newName, newConString, newProviderName);
101             // 打開可執行的配置文件*.exe.config
102             Configuration config =
103                 ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
104             // 如果連接串已存在,首先刪除它
105             if (isModified)
106             {
107                 config.ConnectionStrings.ConnectionStrings.Remove(newName);
108             }
109             // 將新的連接串添加到配置文件中.
110             config.ConnectionStrings.ConnectionStrings.Add(mySettings);
111             // 保存對配置文件所作的更改
112             config.Save(ConfigurationSaveMode.Modified);
113             // 強制重新載入配置文件的ConnectionStrings配置節
114             ConfigurationManager.RefreshSection("ConnectionStrings");
115         }
116     }
117 }

最后右擊項目選擇“添加-新建項”,然后選擇“應用程序配置文件”,點擊添加按鈕就創建配置文件app.config。

app.config的格式如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="SosoftKey" value="sosoftValue" />
    <add key="SosoftURL" value="sosoft.cnblogs.com" />
    <add key="SosoftProject" value="sosoft.codeplex.com" />
  </appSettings>
</configuration>

按F5運行,可以添加、修改appSettings配置項和列出所有appSettings配置項。

 

柔城配置文件讀寫實例源代碼下載地址:http://files.cnblogs.com/sosoft/SosoftConfig.rar


免責聲明!

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



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