当前位置:网站首页>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
边栏推荐
- Pytorch(三) —— 函数优化
- 细数软件研发效能的七宗罪
- 科研狗可能需要的一些工具
- How to view the changes and opportunities in the construction of smart cities?
- RDF query language SPARQL
- 【硬十宝典】——1.【基础知识】电源的分类
- 总结全了,低代码还需要解决这4点问题
- Announcement on the list of Guangdong famous high-tech products to be selected in 2021
- 神经网络-卷积层
- C language games (I) -- guessing games
猜你喜欢
C - detailed explanation of operators and summary of use cases
STM32 光敏电阻传感器&两路AD采集
Pytest automated testing - compare robotframework framework
Grey correlation cases and codes
2022年煤气考试题库及在线模拟考试
VIM简易使用教程
2022.2.7-2.13 AI industry weekly (issue 84): family responsibilities
Dede collection plug-in does not need to write rules
VR线上展览所具备应用及特色
The longest increasing subsequence and its optimal solution, total animal weight problem
随机推荐
Pytorch(三) —— 函数优化
Pytorch(四) —— 可视化工具 Visdom
2022 hoisting machinery command registration examination and hoisting machinery command examination registration
Take a cold bath
C - detailed explanation of operators and summary of use cases
神经网络的基本骨架-nn.Moudle的使用
Quelques outils dont les chiens scientifiques pourraient avoir besoin
Registration for R2 mobile pressure vessel filling test in 2022 and R2 mobile pressure vessel filling free test questions
How to use maixll dock
CUDA development and debugging tool
Advanced application of ES6 modular and asynchronous programming
Common interview questions ①
I also gave you the MySQL interview questions of Boda factory. If you need to come in and take your own
常用的Transforms中的方法
神经网络-最大池化的使用
2022年T电梯修理题库及模拟考试
Extension fragment
Question bank and answers for chemical automation control instrument operation certificate examination in 2022
2022 tea master (intermediate) examination question bank and tea master (intermediate) examination questions and analysis
最长递增子序列及最优解、动物总重量问题