.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配置项。

柔城配置文件读写实例源代码下载地址:https://files.cnblogs.com/sosoft/SosoftConfig.rar

原文地址:https://www.cnblogs.com/sosoft/p/sosoftconfighelper.html