• C#读写应用程序配置文件App.exe.config,并在界面上显示


    C#读写应用程序配置文件App.exe.config,本质是xml文件的读写。

    我们将配置文件的AppSettings节点和ConnectionStrings节点内容自动绑定到分组框控件GroupBox中,同时可以批量保存。

    一、新建Windows窗体应用程序SaveDefaultXmlConfigDemo,将默认的Form1重命名为FormSaveDefaultXmlConfig。

    窗体 FormSaveDefaultXmlConfig设计如图:

     添加对System.Configuration的引用。

    为窗体FormSaveDefaultXmlConfig绑定Load事件FormSaveDefaultXmlConfig_Load

    为按钮btnSaveConfig绑定事件btnSaveConfig_Click。

    二、默认的应用程序配置文件App.config配置如下:

    1. <?xml version="1.0" encoding="utf-8" ?>
    2. <configuration>
    3. <startup>
    4. <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    5. </startup>
    6. <appSettings>
    7. <add key="SoftName" value="Sword7" />
    8. <add key="Supplier" value="SoftStar" />
    9. <add key="EnabledTcp" value="1" />
    10. </appSettings>
    11. <connectionStrings>
    12. <add name="DataConnect" providerName="MySql.Data" connectionString="server=127.0.0.1;Database=test;Uid=root;Pwd=root;" />
    13. <add name="ExternalConnect" providerName="System.Data.SqlClient" connectionString="server=127.0.0.1;Database=external;Uid=root;Pwd=123456;" />
    14. </connectionStrings>
    15. </configuration>

    三、窗体FormSaveDefaultXmlConfig源程序如下

    (忽略设计器自动生成的代码):

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Configuration;
    5. using System.Data;
    6. using System.Drawing;
    7. using System.Linq;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. using System.Windows.Forms;
    11. namespace SaveDefaultXmlConfigDemo
    12. {
    13. public partial class FormSaveDefaultXmlConfig : Form
    14. {
    15. public FormSaveDefaultXmlConfig()
    16. {
    17. InitializeComponent();
    18. //添加引用System.Configuration
    19. }
    20. private void btnSaveConfig_Click(object sender, EventArgs e)
    21. {
    22. try
    23. {
    24. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    25. List<Tuple<string, string>> tupleAppSettings = GetAppSettingList();
    26. for (int i = 0; i < tupleAppSettings.Count; i++)
    27. {
    28. //修改配置节点AppSettings的内容
    29. config.AppSettings.Settings[tupleAppSettings[i].Item1].Value = tupleAppSettings[i].Item2;
    30. }
    31. List<Tuple<string, string, string>> tupleConnectionStrings = GetConnectionStringList();
    32. for (int i = 0; i < tupleConnectionStrings.Count; i++)
    33. {
    34. //修改配置节点ConnectionStrings的内容
    35. config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ProviderName = tupleConnectionStrings[i].Item2;
    36. config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ConnectionString = tupleConnectionStrings[i].Item3;
    37. }
    38. //保存配置文件
    39. config.Save();
    40. MessageBox.Show($"保存应用程序配置文件成功,开始重新加载应用程序配置.", "提示");
    41. //刷新配置
    42. FormSaveDefaultXmlConfig_Load(null, e);
    43. }
    44. catch (Exception ex)
    45. {
    46. MessageBox.Show($"保存应用程序配置文件出错:{ex.Message}", "出错");
    47. }
    48. }
    49. /// <summary>
    50. /// 获取配置节点AppSettings的所有内容,将其添加到元组列表中
    51. /// </summary>
    52. /// <returns></returns>
    53. private List<Tuple<string, string>> GetAppSettingList()
    54. {
    55. List<Tuple<string, string>> tupleAppSettings = new List<Tuple<string, string>>();
    56. for (int i = 0; i < groupBox1.Controls.Count; i++)
    57. {
    58. if (groupBox1.Controls[i] is Label lbl)
    59. {
    60. Control[] controls = groupBox1.Controls.Find($"txtValue{lbl.Tag}", true);
    61. if (controls == null || controls.Length == 0)
    62. {
    63. throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【txtValue{lbl.Tag}】");
    64. }
    65. tupleAppSettings.Add(Tuple.Create(lbl.Text, controls[0].Text));
    66. }
    67. }
    68. return tupleAppSettings;
    69. }
    70. /// <summary>
    71. /// 获取配置节点onnectionStrings的所有内容,将其添加到元组列表中
    72. /// </summary>
    73. /// <returns></returns>
    74. private List<Tuple<string, string, string>> GetConnectionStringList()
    75. {
    76. List<Tuple<string, string, string>> tupleConnectionStrings = new List<Tuple<string, string, string>>();
    77. for (int i = 0; i < groupBox2.Controls.Count; i++)
    78. {
    79. if (groupBox2.Controls[i] is Label lbl && lbl.Name.StartsWith("lblName"))
    80. {
    81. Control[] controlProviderNames = groupBox2.Controls.Find($"txtProviderName{lbl.Tag}", true);
    82. if (controlProviderNames == null || controlProviderNames.Length == 0)
    83. {
    84. throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【txtProviderName{lbl.Tag}】");
    85. }
    86. Control[] controlConnectionStrings = groupBox2.Controls.Find($"txtConnectionString{lbl.Tag}", true);
    87. if (controlConnectionStrings == null || controlConnectionStrings.Length == 0)
    88. {
    89. throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【txtConnectionString{lbl.Tag}】");
    90. }
    91. tupleConnectionStrings.Add(Tuple.Create(lbl.Text, controlProviderNames[0].Text, controlConnectionStrings[0].Text));
    92. }
    93. }
    94. return tupleConnectionStrings;
    95. }
    96. private void FormSaveDefaultXmlConfig_Load(object sender, EventArgs e)
    97. {
    98. try
    99. {
    100. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    101. txtFilePath.Text = config.FilePath;
    102. //读取配置AppSetting节点,
    103. KeyValueConfigurationCollection keyValueCollection = config.AppSettings.Settings;
    104. AddAppSettingConfig(keyValueCollection);
    105. //读取连接字符串ConnectionStrings节点
    106. ConnectionStringSettingsCollection connectionCollection = config.ConnectionStrings.ConnectionStrings;
    107. AddConnectionStringConfig(connectionCollection);
    108. }
    109. catch (Exception ex)
    110. {
    111. MessageBox.Show($"加载应用程序配置文件出错:{ex.Message}", "出错");
    112. }
    113. }
    114. /// <summary>
    115. /// 读取所有的AppSetting节点,将其绑定到groupBox1中
    116. /// 只考虑在配置文件中【IsPresent为true】的节点
    117. /// </summary>
    118. /// <param name="keyValueCollection"></param>
    119. private void AddAppSettingConfig(KeyValueConfigurationCollection keyValueCollection)
    120. {
    121. groupBox1.Controls.Clear();
    122. int index = 0;
    123. foreach (KeyValueConfigurationElement keyValueElement in keyValueCollection)
    124. {
    125. ElementInformation elemInfo = keyValueElement.ElementInformation;
    126. if (!elemInfo.IsPresent)
    127. {
    128. //考虑到部分配置不是在App.exe.config配置文件中,此时不做处理
    129. continue;
    130. }
    131. Label label = new Label();
    132. label.AutoSize = true;
    133. label.Location = new System.Drawing.Point(20, 20 + index * 30);
    134. label.Name = $"lblKey{index + 1}";
    135. label.Text = keyValueElement.Key;
    136. label.Tag = index + 1;
    137. TextBox textBox = new TextBox();
    138. textBox.Location = new System.Drawing.Point(120, 20 + index * 30);
    139. textBox.Name = $"txtValue{index + 1}";
    140. textBox.Size = new System.Drawing.Size(300, 21);
    141. textBox.Text = keyValueElement.Value;
    142. groupBox1.Controls.AddRange(new Control[] { label, textBox });
    143. index++;
    144. }
    145. }
    146. /// <summary>
    147. /// 读取所有的ConnectionString节点,将其绑定到groupBox2中
    148. /// 只考虑在配置文件中【IsPresent为true】的节点
    149. /// </summary>
    150. /// <param name="connectionCollection"></param>
    151. private void AddConnectionStringConfig(ConnectionStringSettingsCollection connectionCollection)
    152. {
    153. groupBox2.Controls.Clear();
    154. int index = 0;
    155. foreach (ConnectionStringSettings connectElement in connectionCollection)
    156. {
    157. ElementInformation elemInfo = connectElement.ElementInformation;
    158. if (!elemInfo.IsPresent)
    159. {
    160. //考虑到连接字符串有系统默认配置,不在配置文件中【IsPresent=false】,因此过滤掉,如下面两个
    161. //LocalSqlServer、LocalMySqlServer
    162. continue;
    163. }
    164. Label label = new Label();
    165. label.AutoSize = true;
    166. label.Location = new System.Drawing.Point(20, 20 + index * 30);
    167. label.Name = $"lblName{index + 1}";
    168. label.Text = connectElement.Name;
    169. label.Tag = index + 1;
    170. TextBox textBox = new TextBox();
    171. textBox.Location = new System.Drawing.Point(120, 20 + index * 30);
    172. textBox.Name = $"txtConnectionString{index + 1}";
    173. textBox.Size = new System.Drawing.Size(360, 21);
    174. textBox.Text = connectElement.ConnectionString;
    175. Label lblFixed = new Label();
    176. lblFixed.AutoSize = true;
    177. lblFixed.Location = new System.Drawing.Point(500, 20 + index * 30);
    178. lblFixed.Name = $"lblFixed{index + 1}";
    179. lblFixed.Text = "提供程序名称";
    180. TextBox txtProviderName = new TextBox();
    181. txtProviderName.Location = new System.Drawing.Point(580, 20 + index * 30);
    182. txtProviderName.Name = $"txtProviderName{index + 1}";
    183. txtProviderName.Size = new System.Drawing.Size(140, 21);
    184. txtProviderName.Text = connectElement.ProviderName;
    185. groupBox2.Controls.AddRange(new Control[] { label, textBox, lblFixed, txtProviderName });
    186. index++;
    187. }
    188. }
    189. }
    190. }

    四、程序运行如图:

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

  • 相关阅读:
    MySQL主从
    互联网基础结构发展的三个阶段及其特点
    dubbo入门小案例
    头条三面技术四面HR,我临危不乱,顺顺利利一周拿下!
    PMP考试提分必刷题
    使用 SAP UI5 ABAP Repository 部署本地 SAP UI5 应用到 ABAP 服务器的单步调试
    python多线程系列—Queue对象(五)
    软件测试实战项目,问题答疑
    react 大杂烩
    java-php-net-python-商务安全邮箱计算机毕业设计程序
  • 原文地址:https://blog.csdn.net/ylq1045/article/details/125513502