当前位置:网站首页>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

边栏推荐
- MySQL winter vacation self-study 2022 12 (5)
- Registration for R2 mobile pressure vessel filling test in 2022 and R2 mobile pressure vessel filling free test questions
- Advanced application of ES6 modular and asynchronous programming
- How do I sort a list of strings in dart- How can I sort a list of strings in Dart?
- STM32 photoresistor sensor & two channel AD acquisition
- C language games (I) -- guessing games
- Construction of Meizhou nursing laboratory: equipment configuration
- 常用的Transforms中的方法
- Summary of testing experience - Testing Theory
- JS rotation chart
猜你喜欢

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

One click shell to automatically deploy any version of redis

The junior college students were angry for 32 days, four rounds of interviews, five hours of soul torture, and won Ali's offer with tears

Fitness without equipment

数据加载及预处理

【硬十宝典】——1.【基础知识】电源的分类

Simple implementation of slf4j

2022年G1工业锅炉司炉特种作业证考试题库及在线模拟考试

分布式全局唯一ID解决方案详解

技术分享| 融合调度中的广播功能设计
随机推荐
LM小型可编程控制器软件(基于CoDeSys)笔记十九:报错does not match the profile of the target
Shell之Unix运维常用命令
Measurement of quadrature axis and direct axis inductance of three-phase permanent magnet synchronous motor
How to view the changes and opportunities in the construction of smart cities?
常用的Transforms中的方法
技术分享| 融合调度中的广播功能设计
2022 hoisting machinery command registration examination and hoisting machinery command examination registration
Pytorch(四) —— 可视化工具 Visdom
2022年上海市安全员C证考试题模拟考试题库及答案
PgSQL failed to start after installation
Execution failed for task ‘:app:processDebugResources‘. > A failure occurred while executing com. and
All in all, the low code still needs to solve these four problems
2022年G1工业锅炉司炉特种作业证考试题库及在线模拟考试
Cmake selecting compilers and setting compiler options
2022年聚合工艺考试题及模拟考试
Why is Hong Kong server most suitable for overseas website construction
分布式架构系统拆分原则、需求、微服务拆分步骤
Day 52 - tree problem
Registration for R2 mobile pressure vessel filling test in 2022 and R2 mobile pressure vessel filling free test questions
LeetCode_28(实现 strStr())