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

边栏推荐
- 无器械健身
- Construction of Meizhou nursing laboratory: equipment configuration
- Talk about testdeploy
- Summary of acl2021 information extraction related papers
- How to do the performance pressure test of "Health Code"
- Strategic suggestions and future development trend of global and Chinese vibration isolator market investment report 2022 Edition
- Section 27 remote access virtual private network workflow and experimental demonstration
- Openresty rewrites the location of 302
- CUDA development and debugging tool
- C -- array
猜你喜欢

JVM栈和堆简介

测量三相永磁同步电机的交轴直轴电感

VIM easy to use tutorial

VR线上展览所具备应用及特色

扩展-Fragment

Strategic suggestions and future development trend of global and Chinese vibration isolator market investment report 2022 Edition

Ten wastes of software research and development: the other side of research and development efficiency

2022年煤气考试题库及在线模拟考试

pytorch 卷积操作
![[pat (basic level) practice] - [simple simulation] 1064 friends](/img/37/0ef0f8aae15ae574be1d76c97497c9.jpg)
[pat (basic level) practice] - [simple simulation] 1064 friends
随机推荐
C - detailed explanation of operators and summary of use cases
【硬十宝典】——1.【基础知识】电源的分类
JS image path conversion Base64 format
STM32扩展板 温度传感器和温湿度传感器的使用
Annual inventory review of Alibaba cloud's observable practices in 2021
Question bank and online simulation examination for special operation certificate of G1 industrial boiler stoker in 2022
2022.2.7-2.13 AI industry weekly (issue 84): family responsibilities
Pytest automated testing - compare robotframework framework
Leecode record 1351 negative numbers in statistical ordered matrix
测量三相永磁同步电机的交轴直轴电感
JVM栈和堆简介
Question bank and answers for chemical automation control instrument operation certificate examination in 2022
STM32 光敏电阻传感器&两路AD采集
[FTP] common FTP commands, updating continuously
Difficulties in the development of knowledge map & the importance of building industry knowledge map
解决qiankun中子应用外链文件无法获取
细数软件研发效能的七宗罪
LeetCode_53(最大子数组和)
Pytorch(二) —— 激活函数、损失函数及其梯度
2022 a special equipment related management (elevator) simulation test and a special equipment related management (elevator) certificate examination