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

 更新时间:2023年06月16日 16:37:24   作者:斯内科  
这篇文章主要介绍了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配置如下

<?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>

三、窗体FormSaveDefaultXmlConfig源程序如下

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

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();
            //添加引用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++)
                {
                    //修改配置节点AppSettings的内容
                    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++)
                {
                    //修改配置节点ConnectionStrings的内容
                    config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ProviderName = tupleConnectionStrings[i].Item2;
                    config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ConnectionString = tupleConnectionStrings[i].Item3;
                }
                //保存配置文件
                config.Save();
                MessageBox.Show($"保存应用程序配置文件成功,开始重新加载应用程序配置.", "提示");
                //刷新配置
                FormSaveDefaultXmlConfig_Load(null, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存应用程序配置文件出错:{ex.Message}", "出错");
            }
        }
        /// <summary>
        /// 获取配置节点AppSettings的所有内容,将其添加到元组列表中
        /// </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($"没有找到【{lbl.Text}】对应的文本框控件【txtValue{lbl.Tag}】");
                    }
                    tupleAppSettings.Add(Tuple.Create(lbl.Text, controls[0].Text));
                }
            }
            return tupleAppSettings;
        }
        /// <summary>
        /// 获取配置节点onnectionStrings的所有内容,将其添加到元组列表中
        /// </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($"没有找到【{lbl.Text}】对应的文本框控件【txtProviderName{lbl.Tag}】");
                    }
                    Control[] controlConnectionStrings = groupBox2.Controls.Find($"txtConnectionString{lbl.Tag}", true);
                    if (controlConnectionStrings == null || controlConnectionStrings.Length == 0)
                    {
                        throw new Exception($"没有找到【{lbl.Text}】对应的文本框控件【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;
                //读取配置AppSetting节点,
                KeyValueConfigurationCollection keyValueCollection = config.AppSettings.Settings;
                AddAppSettingConfig(keyValueCollection);
                //读取连接字符串ConnectionStrings节点
                ConnectionStringSettingsCollection connectionCollection = config.ConnectionStrings.ConnectionStrings;
                AddConnectionStringConfig(connectionCollection);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载应用程序配置文件出错:{ex.Message}", "出错");
            }
        }
        /// <summary>
        /// 读取所有的AppSetting节点,将其绑定到groupBox1中
        /// 只考虑在配置文件中【IsPresent为true】的节点
        /// </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)
                {
                    //考虑到部分配置不是在App.exe.config配置文件中,此时不做处理
                    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>
        /// 读取所有的ConnectionString节点,将其绑定到groupBox2中
        /// 只考虑在配置文件中【IsPresent为true】的节点
        /// </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)
                {
                    //考虑到连接字符串有系统默认配置,不在配置文件中【IsPresent=false】,因此过滤掉,如下面两个
                    //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 = "提供程序名称";
                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++;
            }
        }
    }
}

四、程序运行如图

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • C#编程实现对象与JSON串互相转换实例分析

    C#编程实现对象与JSON串互相转换实例分析

    这篇文章主要介绍了C#编程实现对象与JSON串互相转换的方法,结合实例分析了在DoNet2.0与Donet3.5环境下实现对象与JSON转换的相关技巧,需要的朋友可以参考下
    2015-11-11
  • C#标识符的使用小结

    C#标识符的使用小结

    C#标识符还是比较常见的东西,这里我们主要介绍C#标识符中的用法,包括介绍 static 的方法和bool 的形参等方面
    2014-01-01
  • Visual Studio 中自定义代码片段的方法

    Visual Studio 中自定义代码片段的方法

    这篇文章主要介绍了Visual Studio 中自定义代码片段的方法,本文分步骤通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • C#实现动态图标闪烁显示的示例代码

    C#实现动态图标闪烁显示的示例代码

    这篇文章主要为大家详细介绍了如何利用C#实现动态图标闪烁显示的功能,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以了解一下
    2022-12-12
  • C#生成带logo的二维码

    C#生成带logo的二维码

    带logo的二维码生成分为两步骤:首先根据输入的内容生成二维码图片,然后读取本地的logo图片,通过图片处理生成带logo的二维码。本文对此进行介绍,具有很好的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • C# Winform 子窗体访问父级窗体的控件和属性

    C# Winform 子窗体访问父级窗体的控件和属性

    本文主要介绍两种子窗体访问父窗体控件和属性的方法,大家可以参考一下,本人比较偏向第二种,把父窗体作为属性传递,一劳永逸,想访问父窗体的什么控件属性都可以。
    2016-05-05
  • c#与mysql的连接

    c#与mysql的连接

    c#与mysql的连接...
    2007-03-03
  • 浅析C#中goto跳转语句的用法

    浅析C#中goto跳转语句的用法

    在我们日常工作中常用的C#跳转语句有break、continue、return,但是还有一个C#跳转语句很多同学可能都比较的陌生就是goto,下面我们就来看看goto跳转语句的用法吧
    2024-03-03
  • 详解C#中HashTable的用法

    详解C#中HashTable的用法

    在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值
    2016-02-02
  • C#中的HttpWebRequest类介绍

    C#中的HttpWebRequest类介绍

    本文详细讲解了C#中的HttpWebRequest类,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-01-01

最新评论