当前位置:网站首页>C read / write application configuration file app exe. Config and display it on the interface
C read / write application configuration file app exe. Config and display it on the interface
2022-07-01 04:44:00 【Sri Lanka internal medicine】
C# Read and write application configuration files App.exe.config, The essence is xml Reading and writing of documents .
We will configure the AppSettings Nodes and ConnectionStrings The content of the node is automatically bound to the grouping box control GroupBox in , At the same time, it can be saved in batches .
One 、 newly build Windows Forms application SaveDefaultXmlConfigDemo, Default Form1 Rename it to FormSaveDefaultXmlConfig.
forms FormSaveDefaultXmlConfig The design is shown in the picture :

Add pair System.Configuration References to .
For form FormSaveDefaultXmlConfig binding Load event FormSaveDefaultXmlConfig_Load
Is a button btnSaveConfig The binding event btnSaveConfig_Click.
Two 、 Default application configuration file App.config The configuration is as follows :
<?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>3、 ... and 、 forms FormSaveDefaultXmlConfig The source program is as follows
( Ignore the code automatically generated by the designer ):
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();
// Add reference 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++)
{
// Modify the configuration node AppSettings The content of
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++)
{
// Modify the configuration node ConnectionStrings The content of
config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ProviderName = tupleConnectionStrings[i].Item2;
config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ConnectionString = tupleConnectionStrings[i].Item3;
}
// Save configuration file
config.Save();
MessageBox.Show($" Saving application configuration file succeeded , Start reloading the application configuration .", " Tips ");
// Refresh configuration
FormSaveDefaultXmlConfig_Load(null, e);
}
catch (Exception ex)
{
MessageBox.Show($" Error saving application configuration file :{ex.Message}", " error ");
}
}
/// <summary>
/// Get configuration node AppSettings All of , Add it to the tuple list
/// </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($" Can't find 【{lbl.Text}】 Corresponding text box control 【txtValue{lbl.Tag}】");
}
tupleAppSettings.Add(Tuple.Create(lbl.Text, controls[0].Text));
}
}
return tupleAppSettings;
}
/// <summary>
/// Get configuration node onnectionStrings All of , Add it to the tuple list
/// </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($" Can't find 【{lbl.Text}】 Corresponding text box control 【txtProviderName{lbl.Tag}】");
}
Control[] controlConnectionStrings = groupBox2.Controls.Find($"txtConnectionString{lbl.Tag}", true);
if (controlConnectionStrings == null || controlConnectionStrings.Length == 0)
{
throw new Exception($" Can't find 【{lbl.Text}】 Corresponding text box control 【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;
// Reading configuration AppSetting node ,
KeyValueConfigurationCollection keyValueCollection = config.AppSettings.Settings;
AddAppSettingConfig(keyValueCollection);
// Read connection string ConnectionStrings node
ConnectionStringSettingsCollection connectionCollection = config.ConnectionStrings.ConnectionStrings;
AddConnectionStringConfig(connectionCollection);
}
catch (Exception ex)
{
MessageBox.Show($" Error loading application configuration file :{ex.Message}", " error ");
}
}
/// <summary>
/// Read all AppSetting node , Bind it to groupBox1 in
/// Only consider in the configuration file 【IsPresent by true】 The node of
/// </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)
{
// Considering that some configurations are not in App.exe.config In profile , Do not handle at this time
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>
/// Read all ConnectionString node , Bind it to groupBox2 in
/// Only consider in the configuration file 【IsPresent by true】 The node of
/// </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)
{
// Considering that the connection string has the system default configuration , Not in the configuration file 【IsPresent=false】, So filter out , Like the following two
//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 = " Provider name ";
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++;
}
}
}
}
Four 、 The program runs as shown in the figure :

After modifying and saving the configuration , open SaveDefaultXmlConfigDemo.exe.Config file

边栏推荐
- Seven crimes of counting software R & D Efficiency
- MySQL winter vacation self-study 2022 12 (5)
- Dede collection plug-in does not need to write rules
- Daily algorithm & interview questions, 28 days of special training in large factories - the 13th day (array)
- STM32 photoresistor sensor & two channel AD acquisition
- Talk about testdeploy
- This sideline workload is small, 10-15k, free unlimited massage
- 【FTP】FTP常用命令,持续更新中……
- 解决qiankun中子应用外链文件无法获取
- Advanced application of ES6 modular and asynchronous programming
猜你喜欢

Why is Internet thinking not suitable for AI products?

扩展-Fragment

Question bank and online simulation examination for special operation certificate of G1 industrial boiler stoker in 2022

Basic usage, principle and details of session

About the transmission pipeline of stage in spark

Registration of P cylinder filling examination in 2022 and analysis of P cylinder filling

Shell之一键自动部署Redis任意版本

2022 question bank and answers for safety production management personnel of hazardous chemical production units

The longest increasing subsequence and its optimal solution, total animal weight problem

Odeint et GPU
随机推荐
Common UNIX Operation and maintenance commands of shell
Overview of the construction details of Meizhou veterinary laboratory
分布式数据库数据一致性的原理、与技术实现方案
Registration for R2 mobile pressure vessel filling test in 2022 and R2 mobile pressure vessel filling free test questions
2022年化工自动化控制仪表操作证考试题库及答案
Daily algorithm & interview questions, 28 days of special training in large factories - the 13th day (array)
VR线上展览所具备应用及特色
Take a cold bath
OdeInt與GPU
Pytorch(三) —— 函数优化
技术分享| 融合调度中的广播功能设计
About the transmission pipeline of stage in spark
常用的Transforms中的方法
RuntimeError: mean(): input dtype should be either floating point or complex dtypes.Got Long instead
C - detailed explanation of operators and summary of use cases
2022年聚合工艺考试题及模拟考试
Question bank and answers for chemical automation control instrument operation certificate examination in 2022
2022年煤气考试题库及在线模拟考试
STM32扩展板 数码管显示
This sideline workload is small, 10-15k, free unlimited massage