最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#如何讀寫應(yīng)用程序配置文件App.exe.config,并在界面上顯示

 更新時(shí)間:2023年06月16日 16:37:24   作者:斯內(nèi)科  
這篇文章主要介紹了C#如何讀寫應(yīng)用程序配置文件App.exe.config,并在界面上顯示問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

C#讀寫應(yīng)用程序配置文件App.exe.config,本質(zhì)是xml文件的讀寫。

我們將配置文件的AppSettings節(jié)點(diǎn)和ConnectionStrings節(jié)點(diǎn)內(nèi)容自動綁定到分組框控件GroupBox中,同時(shí)可以批量保存。

一、新建Windows窗體應(yīng)用程序SaveDefaultXmlConfigDemo

將默認(rèn)的Form1重命名為FormSaveDefaultXmlConfig。

窗體 FormSaveDefaultXmlConfig設(shè)計(jì)如圖:

添加對System.Configuration的引用。

為窗體FormSaveDefaultXmlConfig綁定Load事件FormSaveDefaultXmlConfig_Load

為按鈕btnSaveConfig綁定事件btnSaveConfig_Click。

二、默認(rèn)的應(yīng)用程序配置文件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源程序如下

(忽略設(shè)計(jì)器自動生成的代碼)

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++)
                {
                    //修改配置節(jié)點(diǎn)AppSettings的內(nèi)容
                    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++)
                {
                    //修改配置節(jié)點(diǎn)ConnectionStrings的內(nèi)容
                    config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ProviderName = tupleConnectionStrings[i].Item2;
                    config.ConnectionStrings.ConnectionStrings[tupleConnectionStrings[i].Item1].ConnectionString = tupleConnectionStrings[i].Item3;
                }
                //保存配置文件
                config.Save();
                MessageBox.Show($"保存應(yīng)用程序配置文件成功,開始重新加載應(yīng)用程序配置.", "提示");
                //刷新配置
                FormSaveDefaultXmlConfig_Load(null, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存應(yīng)用程序配置文件出錯:{ex.Message}", "出錯");
            }
        }
        /// <summary>
        /// 獲取配置節(jié)點(diǎn)AppSettings的所有內(nèi)容,將其添加到元組列表中
        /// </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}】對應(yīng)的文本框控件【txtValue{lbl.Tag}】");
                    }
                    tupleAppSettings.Add(Tuple.Create(lbl.Text, controls[0].Text));
                }
            }
            return tupleAppSettings;
        }
        /// <summary>
        /// 獲取配置節(jié)點(diǎn)onnectionStrings的所有內(nèi)容,將其添加到元組列表中
        /// </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}】對應(yīng)的文本框控件【txtProviderName{lbl.Tag}】");
                    }
                    Control[] controlConnectionStrings = groupBox2.Controls.Find($"txtConnectionString{lbl.Tag}", true);
                    if (controlConnectionStrings == null || controlConnectionStrings.Length == 0)
                    {
                        throw new Exception($"沒有找到【{lbl.Text}】對應(yīng)的文本框控件【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節(jié)點(diǎn),
                KeyValueConfigurationCollection keyValueCollection = config.AppSettings.Settings;
                AddAppSettingConfig(keyValueCollection);
                //讀取連接字符串ConnectionStrings節(jié)點(diǎn)
                ConnectionStringSettingsCollection connectionCollection = config.ConnectionStrings.ConnectionStrings;
                AddConnectionStringConfig(connectionCollection);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加載應(yīng)用程序配置文件出錯:{ex.Message}", "出錯");
            }
        }
        /// <summary>
        /// 讀取所有的AppSetting節(jié)點(diǎn),將其綁定到groupBox1中
        /// 只考慮在配置文件中【IsPresent為true】的節(jié)點(diǎn)
        /// </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配置文件中,此時(shí)不做處理
                    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節(jié)點(diǎn),將其綁定到groupBox2中
        /// 只考慮在配置文件中【IsPresent為true】的節(jié)點(diǎn)
        /// </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)
                {
                    //考慮到連接字符串有系統(tǒng)默認(rèn)配置,不在配置文件中【IsPresent=false】,因此過濾掉,如下面兩個(gè)
                    //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++;
            }
        }
    }
}

四、程序運(yùn)行如圖

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

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • WPF實(shí)現(xiàn)上下滾動字幕效果

    WPF實(shí)現(xiàn)上下滾動字幕效果

    這篇文章主要為大家詳細(xì)介紹了WPF實(shí)現(xiàn)上下滾動字幕效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • C#?WPF中RadioButton控件的用法及應(yīng)用場景

    C#?WPF中RadioButton控件的用法及應(yīng)用場景

    在WPF應(yīng)用程序中,RadioButton控件是一種常用的用戶界面元素,本文主要介紹了C#?WPF中RadioButton控件的用法及應(yīng)用場景,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-03-03
  • 深入理解C#索引器(一種支持參數(shù)的屬性)與屬性的對比

    深入理解C#索引器(一種支持參數(shù)的屬性)與屬性的對比

    本篇文章是對C#索引器(一種支持參數(shù)的屬性)與屬性的對比進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • C#設(shè)計(jì)模式實(shí)現(xiàn)之迭代器模式

    C#設(shè)計(jì)模式實(shí)現(xiàn)之迭代器模式

    迭代器模式把對象的職責(zé)分離,職責(zé)分離可以最大限度減少彼此之間的耦合程度,從而建立一個(gè)松耦合的對象,這篇文章主要給大家介紹了關(guān)于C#設(shè)計(jì)模式實(shí)現(xiàn)之迭代器模式的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • C#使用Stack<T>進(jìn)行堆棧設(shè)計(jì)的實(shí)現(xiàn)

    C#使用Stack<T>進(jìn)行堆棧設(shè)計(jì)的實(shí)現(xiàn)

    堆棧代表了一個(gè)后進(jìn)先出的對象集合,當(dāng)您需要對各項(xiàng)進(jìn)行后進(jìn)先出的訪問時(shí),則使用堆棧,本文主要介紹了C#使用Stack<T>類進(jìn)行堆棧設(shè)計(jì)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),感興趣的可以了解一下
    2024-03-03
  • C#設(shè)置子窗體在主窗體中居中顯示解決方案

    C#設(shè)置子窗體在主窗體中居中顯示解決方案

    接下來將介紹C#如何設(shè)置子窗體在主窗體中居中顯示,本文提供詳細(xì)的操作步驟,需要的朋友可以參考下
    2012-12-12
  • C#中ref關(guān)鍵字的用法

    C#中ref關(guān)鍵字的用法

    這篇文章介紹了C#中ref關(guān)鍵字的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-07-07
  • C#中實(shí)現(xiàn)查找mysql的安裝路徑

    C#中實(shí)現(xiàn)查找mysql的安裝路徑

    這篇文章主要介紹了C#中實(shí)現(xiàn)查找mysql的安裝路徑,本文講解使用SQL語句查詢出mysql的安裝路徑,方便在備份時(shí)使用,需要的朋友可以參考下
    2015-06-06
  • C#清除WebBrowser中Cookie緩存的方法

    C#清除WebBrowser中Cookie緩存的方法

    這篇文章主要介紹了C#清除WebBrowser中Cookie緩存的方法,涉及C#針對WebBrowser控件的操作技巧,非常簡單實(shí)用,需要的朋友可以參考下
    2016-05-05
  • C#實(shí)現(xiàn)Word轉(zhuǎn)換TXT的方法詳解

    C#實(shí)現(xiàn)Word轉(zhuǎn)換TXT的方法詳解

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)Word轉(zhuǎn)換TXT的功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下
    2022-12-12

最新評論

同德县| 庆城县| 太谷县| 会东县| 海晏县| 当阳市| 太仓市| 泰顺县| 桃园市| 宁夏| 漳平市| 泗洪县| 丰台区| 昭通市| 闸北区| 耿马| 安阳市| 曲周县| 古蔺县| 永福县| 视频| 莱阳市| 万安县| 青神县| 贺州市| 天柱县| 永定县| 五峰| 鄂尔多斯市| 博客| 长乐市| 阳东县| 库车县| 繁峙县| 云和县| 天水市| 禹城市| 东台市| 五河县| 宁河县| 岱山县|