C#如何讀寫應用程序配置文件App.exe.config,并在界面上顯示
C#讀寫應用程序配置文件App.exe.config,本質(zhì)是xml文件的讀寫。
我們將配置文件的AppSettings節(jié)點和ConnectionStrings節(jié)點內(nèi)容自動綁定到分組框控件GroupBox中,同時可以批量保存。
一、新建Windows窗體應用程序SaveDefaultXmlConfigDemo
將默認的Form1重命名為FormSaveDefaultXmlConfig。
窗體 FormSaveDefaultXmlConfig設計如圖:

添加對System.Configuration的引用。
為窗體FormSaveDefaultXmlConfig綁定Load事件FormSaveDefaultXmlConfig_Load
為按鈕btnSaveConfig綁定事件btnSaveConfig_Click。
二、默認的應用程序配置文件App.config配置如下
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="SoftName" value="Sword7" />
<add key="Supplier" value="SoftStar" />
<add key="EnabledTcp" value="1" />
</appSettings>
<connectionStrings>
<add name="DataConnect" providerName="MySql.Data" connectionString="server=127.0.0.1;Database=test;Uid=root;Pwd=root;" />
<add name="ExternalConnect" providerName="System.Data.SqlClient" connectionString="server=127.0.0.1;Database=external;Uid=root;Pwd=123456;" />
</connectionStrings>
</configuration>三、窗體FormSaveDefaultXmlConfig源程序如下
(忽略設計器自動生成的代碼)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SaveDefaultXmlConfigDemo
{
public partial class FormSaveDefaultXmlConfig : Form
{
public FormSaveDefaultXmlConfig()
{
InitializeComponent();
//添加引用System.Configuration
}
private void btnSaveConfig_Click(object sender, EventArgs e)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
List<Tuple<string, string>> tupleAppSettings = GetAppSettingList();
for (int i = 0; i < tupleAppSettings.Count; i++)
{
//修改配置節(jié)點AppSettings的內(nèi)容
config.AppSettings.Settings[tupleAppSettings[i].Item1].Value = tupleAppSettings[i].Item2;
}
List<Tuple<string, string, string>> tupleConnectionStrings = GetConnectionStringList();
for (int i = 0; i < tupleConnectionStrings.Count; i++)
{
//修改配置節(jié)點ConnectionStrings的內(nèi)容
config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ProviderName = tupleConnectionStrings[i].Item2;
config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ConnectionString = tupleConnectionStrings[i].Item3;
}
//保存配置文件
config.Save();
MessageBox.Show($"保存應用程序配置文件成功,開始重新加載應用程序配置.", "提示");
//刷新配置
FormSaveDefaultXmlConfig_Load(null, e);
}
catch (Exception ex)
{
MessageBox.Show($"保存應用程序配置文件出錯:{ex.Message}", "出錯");
}
}
/// <summary>
/// 獲取配置節(jié)點AppSettings的所有內(nèi)容,將其添加到元組列表中
/// </summary>
/// <returns></returns>
private List<Tuple<string, string>> GetAppSettingList()
{
List<Tuple<string, string>> tupleAppSettings = new List<Tuple<string, string>>();
for (int i = 0; i < groupBox1.Controls.Count; i++)
{
if (groupBox1.Controls[i] is Label lbl)
{
Control[] controls = groupBox1.Controls.Find($"txtValue{lbl.Tag}", true);
if (controls == null || controls.Length == 0)
{
throw new Exception($"沒有找到【{lbl.Text}】對應的文本框控件【txtValue{lbl.Tag}】");
}
tupleAppSettings.Add(Tuple.Create(lbl.Text, controls[0].Text));
}
}
return tupleAppSettings;
}
/// <summary>
/// 獲取配置節(jié)點onnectionStrings的所有內(nèi)容,將其添加到元組列表中
/// </summary>
/// <returns></returns>
private List<Tuple<string, string, string>> GetConnectionStringList()
{
List<Tuple<string, string, string>> tupleConnectionStrings = new List<Tuple<string, string, string>>();
for (int i = 0; i < groupBox2.Controls.Count; i++)
{
if (groupBox2.Controls[i] is Label lbl && lbl.Name.StartsWith("lblName"))
{
Control[] controlProviderNames = groupBox2.Controls.Find($"txtProviderName{lbl.Tag}", true);
if (controlProviderNames == null || controlProviderNames.Length == 0)
{
throw new Exception($"沒有找到【{lbl.Text}】對應的文本框控件【txtProviderName{lbl.Tag}】");
}
Control[] controlConnectionStrings = groupBox2.Controls.Find($"txtConnectionString{lbl.Tag}", true);
if (controlConnectionStrings == null || controlConnectionStrings.Length == 0)
{
throw new Exception($"沒有找到【{lbl.Text}】對應的文本框控件【txtConnectionString{lbl.Tag}】");
}
tupleConnectionStrings.Add(Tuple.Create(lbl.Text, controlProviderNames[0].Text, controlConnectionStrings[0].Text));
}
}
return tupleConnectionStrings;
}
private void FormSaveDefaultXmlConfig_Load(object sender, EventArgs e)
{
try
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
txtFilePath.Text = config.FilePath;
//讀取配置AppSetting節(jié)點,
KeyValueConfigurationCollection keyValueCollection = config.AppSettings.Settings;
AddAppSettingConfig(keyValueCollection);
//讀取連接字符串ConnectionStrings節(jié)點
ConnectionStringSettingsCollection connectionCollection = config.ConnectionStrings.ConnectionStrings;
AddConnectionStringConfig(connectionCollection);
}
catch (Exception ex)
{
MessageBox.Show($"加載應用程序配置文件出錯:{ex.Message}", "出錯");
}
}
/// <summary>
/// 讀取所有的AppSetting節(jié)點,將其綁定到groupBox1中
/// 只考慮在配置文件中【IsPresent為true】的節(jié)點
/// </summary>
/// <param name="keyValueCollection"></param>
private void AddAppSettingConfig(KeyValueConfigurationCollection keyValueCollection)
{
groupBox1.Controls.Clear();
int index = 0;
foreach (KeyValueConfigurationElement keyValueElement in keyValueCollection)
{
ElementInformation elemInfo = keyValueElement.ElementInformation;
if (!elemInfo.IsPresent)
{
//考慮到部分配置不是在App.exe.config配置文件中,此時不做處理
continue;
}
Label label = new Label();
label.AutoSize = true;
label.Location = new System.Drawing.Point(20, 20 + index * 30);
label.Name = $"lblKey{index + 1}";
label.Text = keyValueElement.Key;
label.Tag = index + 1;
TextBox textBox = new TextBox();
textBox.Location = new System.Drawing.Point(120, 20 + index * 30);
textBox.Name = $"txtValue{index + 1}";
textBox.Size = new System.Drawing.Size(300, 21);
textBox.Text = keyValueElement.Value;
groupBox1.Controls.AddRange(new Control[] { label, textBox });
index++;
}
}
/// <summary>
/// 讀取所有的ConnectionString節(jié)點,將其綁定到groupBox2中
/// 只考慮在配置文件中【IsPresent為true】的節(jié)點
/// </summary>
/// <param name="connectionCollection"></param>
private void AddConnectionStringConfig(ConnectionStringSettingsCollection connectionCollection)
{
groupBox2.Controls.Clear();
int index = 0;
foreach (ConnectionStringSettings connectElement in connectionCollection)
{
ElementInformation elemInfo = connectElement.ElementInformation;
if (!elemInfo.IsPresent)
{
//考慮到連接字符串有系統(tǒng)默認配置,不在配置文件中【IsPresent=false】,因此過濾掉,如下面兩個
//LocalSqlServer、LocalMySqlServer
continue;
}
Label label = new Label();
label.AutoSize = true;
label.Location = new System.Drawing.Point(20, 20 + index * 30);
label.Name = $"lblName{index + 1}";
label.Text = connectElement.Name;
label.Tag = index + 1;
TextBox textBox = new TextBox();
textBox.Location = new System.Drawing.Point(120, 20 + index * 30);
textBox.Name = $"txtConnectionString{index + 1}";
textBox.Size = new System.Drawing.Size(360, 21);
textBox.Text = connectElement.ConnectionString;
Label lblFixed = new Label();
lblFixed.AutoSize = true;
lblFixed.Location = new System.Drawing.Point(500, 20 + index * 30);
lblFixed.Name = $"lblFixed{index + 1}";
lblFixed.Text = "提供程序名稱";
TextBox txtProviderName = new TextBox();
txtProviderName.Location = new System.Drawing.Point(580, 20 + index * 30);
txtProviderName.Name = $"txtProviderName{index + 1}";
txtProviderName.Size = new System.Drawing.Size(140, 21);
txtProviderName.Text = connectElement.ProviderName;
groupBox2.Controls.AddRange(new Control[] { label, textBox, lblFixed, txtProviderName });
index++;
}
}
}
}四、程序運行如圖

修改保存配置后,打開SaveDefaultXmlConfigDemo.exe.Config文件

總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Winform基于多線程實現(xiàn)每隔1分鐘執(zhí)行一段代碼
這篇文章主要介紹了Winform基于多線程實現(xiàn)每隔1分鐘執(zhí)行一段代碼的方法,設計線程的操作及時間函數(shù)的用法,需要的朋友可以參考下2014-10-10
C# IDE VS2005中的Hosting Process (vshost.exe)作用介紹
這篇文章主要介紹了C# IDE VS2005中的Hosting Process (vshost.exe)作用介紹,vshost.exe是一個宿主進程,主要用來提高調(diào)試效率,需要的朋友可以參考下2015-01-01
C#中JavaScriptSerializer幫助類用法實例
這篇文章主要介紹了C#中JavaScriptSerializer幫助類用法,實例分析了JavaScriptSerializer幫助類處理json字符串時的技巧,需要的朋友可以參考下2014-12-12
在C#中調(diào)用VBScript、javascript等腳本的實現(xiàn)代碼
在C#中調(diào)用VBScript、javascript等腳本的實現(xiàn)步驟,需要的朋友可以參考下。2009-11-11
DevExpress實現(xiàn)自定義TreeListNode的Tooltip的方法
這篇文章主要介紹了DevExpress實現(xiàn)自定義TreeListNode的Tooltip的方法,需要的朋友可以參考下2014-08-08

