在Winform中動態讀寫app.config文件

来源:https://www.cnblogs.com/zkwarrior/archive/2023/05/30/17442131.html
-Advertisement-
Play Games

在Winform中動態讀寫app.config文件 https://blog.csdn.net/kingmax54212008/article/details/38987277?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.n ...


在Winform中動態讀寫app.config文件

https://blog.csdn.net/kingmax54212008/article/details/38987277?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-38987277-blog-82746084.235%5Ev36%5Epc_relevant_default_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-38987277-blog-82746084.235%5Ev36%5Epc_relevant_default_base3&utm_relevant_index=12

1、  首先需要在項目中引用:System.Configuration

2、  通過OpenExeConfiguration()這個方法來對配置文件進行操作

     若當前項目的配置文件如下:

複製代碼

  1.   <?xml version="1.0"?>
  2.   <configuration>
  3.   <appSettings>
  4.   <clear />
  5.   <add key="DataSource" value=".\SQL2005"/>
  6.   <!-- 資料庫服務地址-->
  7.   <add key="InitialCatalog" value="db"/>
  8.   <!-- 資料庫名稱-->
  9.   <add key="UserId" value="sa"/>
  10.   <!-- 用戶名-->
  11.   <add key="Password" value="sa"/>
  12.   <!-- 這個密碼是加密之後的-->
  13.   <add key="ConnectTimeout" value="1000"/>
  14.   </appSettings>
  15.   <startup>
  16.   <supportedRuntime version="v2.0.50727"/>
  17.   </startup>
  18.   </configuration>

複製代碼

 

需要對上面appSettings的鍵值作修改,如下代碼所示:

複製代碼

  1.   string path = Application.StartupPath + "\\ASSEMLY.exe";
  2.   Configuration config = ConfigurationManager.OpenExeConfiguration(path);
  3.   config.AppSettings.Settings.Clear();
  4.    
  5.   config.AppSettings.Settings.Add("DataSource", this.DataSource);
  6.   config.AppSettings.Settings.Add("InitialCatalog", this.InitialCatalog);
  7.   config.AppSettings.Settings.Add("UserId", this.UserId);
  8.   config.AppSettings.Settings.Add("Password", this.DePassword);
  9.   config.AppSettings.Settings.Add("ConnectTimeout", this.ConnectTimeout.ToString());
  10.    
  11.   // 保存對配置文件所作的更改
  12.   config.Save(ConfigurationSaveMode.Modified);
  13.   // 強制重新載入配置文件的ConnectionStrings配置節
  14.   ConfigurationManager.RefreshSection("appSettings");

複製代碼

 

  其中它是不能直接修改健值的,是在修改之前要刪除該鍵值,然後重新添加

  同是,上面的只是對AppSettings進行操作,其實也可以對ConnectionStrings、SectionGroups、Sections進行操作

 

讀取所有的AppSettings的值

 

StringBuilder str = new StringBuilder();
str.Append("<table class='isTable'><tr><th></th><th>用戶名</th><th>webservices地址</th><th>webservices方法名稱</th></tr>");
AppSettingsReader reader =
new AppSettingsReader();


NameValueCollection appStgs =
ConfigurationManager.AppSettings;

string[] names =
ConfigurationManager.AppSettings.AllKeys;

String value = String.Empty;

for (int i = 0; i < appStgs.Count; i++)
{


string key = names[i];
if (key.IndexOf("WebSiteUser") >= 0)
{
value = (String)reader.GetValue(key, value.GetType());
string[] strValue = value.Split(',');
string webservices = strValue[0];
string method = strValue[1];
str.Append("<tr><td><a style='color:White;text-decoration: none;' href=\"/sdmin/EditWebSiteUser?key=" + key + "\"><img src='../../Content/icons/admin_edit.png' alt='' title='編輯'/></a></td><td>" + key.Replace("WebSiteUser", "") + "</td><td>" + webservices + "</td><td>" + method + "</td></tr>");
}

}
str.Append("</table>");
ViewData["ListWebSiteUser"] = str;
return View();

Winform—C#讀寫config配置文件

現在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager。並且AppSettings屬性是只讀的,並不支持修改屬性值.

一、如何使用ConfigurationManager?

1、添加引用:添加System.configguration

2、引用空間

3、config配置文件配置節

常用配置節:

(1)普通配置節

<appSettings>  

  <add key="COM1" value="COM1,9600,8,None,1,已啟用" />

</appSettings> 

(2)數據源配置節

<connectionStrings>
  <add name="kyd" connectionString="server=.;database=UFDATA_999_2017;user=sa;pwd=123"/>
</connectionStrings>

(3)自定義配置節

 

 

二、config文件讀寫

1、依據連接串名字connectionName返回數據連接字元串  

複製代碼

//依據連接串名字connectionName返回數據連接字元串  
        public static string GetConnectionStringsConfig(string connectionName)
        {
            //指定config文件讀取
            string file = System.Windows.Forms.Application.ExecutablePath;
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            string connectionString =
                config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
            return connectionString;
        }

複製代碼

2、更新連接字元串  

複製代碼

///<summary> 
        ///更新連接字元串  
        ///</summary> 
        ///<param name="newName">連接字元串名稱</param> 
        ///<param name="newConString">連接字元串內容</param> 
        ///<param name="newProviderName">數據提供程式名稱</param> 
        public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            //指定config文件讀取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //記錄該連接串是否已經存在  
            //如果要更改的連接串已經存在  
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            // 如果連接串已存在,首先刪除它  
            if (exist)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //新建一個連接字元串實例  
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            // 將新的連接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存對配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 強制重新載入配置文件的ConnectionStrings配置節  
            ConfigurationManager.RefreshSection("connectionStrings");
        }

複製代碼

3、返回*.exe.config文件中appSettings配置節的value項  

複製代碼

///<summary> 
        ///返回*.exe.config文件中appSettings配置節的value項  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

複製代碼

4、在*.exe.config文件中appSettings配置節增加一對鍵值對  

複製代碼

///<summary>  
        ///在*.exe.config文件中appSettings配置節增加一對鍵值對  
        ///</summary>  
        ///<param name="newKey"></param>  
        ///<param name="newValue"></param>  
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

複製代碼

5、修改IP地址

// 修改system.serviceModel下所有服務終結點的IP地址
        public static void UpdateServiceModelConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"];
            ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup;
            ClientSection clientSection = serviceModelSectionGroup.Client;
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
                string address = item.Address.ToString();
                string replacement = string.Format("{0}", serverIP);
                address = Regex.Replace(address, pattern, replacement);
                item.Address = new Uri(address);
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

        // 修改applicationSettings中App.Properties.Settings中服務的IP地址
        public static void UpdateConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"];
            ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"];
            ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection;
            if (clientSettingsSection != null)
            {
                SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS");
                if (element1 != null)
                {
                    clientSettingsSection.Settings.Remove(element1);
                    string oldValue = element1.Value.ValueXml.InnerXml;
                    element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element1);
                }

                SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS");
                if (element2 != null)
                {
                    clientSettingsSection.Settings.Remove(element2);
                    string oldValue = element2.Value.ValueXml.InnerXml;
                    element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element2);
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("applicationSettings");
        }

        private static string GetNewIP(string oldValue, string serverIP)
        {
            string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
            string replacement = string.Format("{0}", serverIP);
            string newvalue = Regex.Replace(oldValue, pattern, replacement);
            return newvalue;
        }

修改IP地址

 

config 讀寫方法

複製代碼

using System.Configuration;
//省略其他代碼
public SalesOrderData()
        {
            string str = "";
            str = ConfigurationManager.ConnectionStrings["kyd"].ToString();
            conn = new SqlConnection(str);
            cmd = conn.CreateCommand();
        }

複製代碼

 實際應用:

1、獲取配置節的值

button1 點擊獲取配置節<appSettings>指定key的value值

button2 點擊獲取配置節<connectionStrings>指定name的connectionString值

結果為:

2、修改配置節的值

button1 點擊獲取配置節<appSettings>指定key的value值

button2 點擊修改配置節<connectionStrings>指定key的value值為文本框的值

button3 點擊獲取配置節<appSettings>指定key新的value值

結果為:

 

此時配置文件key1的value值為,獲取key值仍為修改前的值

如何重置為修改前的值?

如何保存修改後的值?


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ## 測試環境: > MySQL版本:8.0 資料庫表:T (主鍵id,唯一索引c,普通欄位d) ![](http://img.javastack.cn/1685072039483867.png) 如果你的業務設計依賴於自增主鍵的連續性,這個設計假設自增主鍵是連續的。但實際上,這樣的假設是錯的,因為 ...
  • 編碼如下:#include <stdio.h> void swap(int* x,int* y ){ int tmp; tmp=*x; *x=*y; *y=tmp ; }; int main(){ int a=4; int b=5; printf("befer\n"); printf("a=%d\n ...
  • @[TOC] # 1.背景 最近項目是國際項目,所以需要經常需要用到UTC時間和local時間的轉換。 所以整理了一下時間戳工具類,方便使用。 這裡主要用到的包就是datatime、time、pytz。 # 2. 遇到的坑 直接看測試案例 ```python tzinfo=pytz.timezone ...
  • 本文將為大家詳細講解Java中Properties配置類怎麼用,這是我們進行開發時經常用到的知識點,也是大家在學習Java中很重要的一個知識點,更是我們在面試時有可能會問到的問題!文章較長,乾貨滿滿,建議大家收藏慢慢學習。文末有本文重點總結,主頁有全系列文章分享。技術類問題,歡迎大家和我們一起交流討... ...
  • SQLAlchemy是著名的ORM(Object Relational Mapping-對象關係映射)框架。其主要作用是在編程中,把面向對象的概念跟資料庫中表的概念對應起來。對許多語言(例如JAVA/PYTHON)來說就是定義一個對象,並且這個對象對應著一張資料庫的表。而這個對象的實例,就對應著表中... ...
  • 摘要:Python Web程式員必看系列,學習如何壓縮 JS 代碼。 本文分享自華為雲社區《Python壓縮JS文件,PythonWeb程式員必看系列,重點是 slimit》,作者: 夢想橡皮擦 。 本篇博客將學習壓縮 JS 代碼,首先要學習的模塊是 jsmin。 jsmin 庫 Python 中的 ...
  • ## 文章首發 [【重學C++】05 | 說透右值引用、移動語義、完美轉發(下)](https://mp.weixin.qq.com/s/w7yXp6efE7_V0EHxXWJiJA) ## 引言 大家好,我是只講技術乾貨的會玩code,今天是【重學C++】的第五講,在第四講《[【重學C++】04 ...
  • 面試題==知識點,這裡所記錄的面試題並不針對於面試者,而是將這些面試題作為技能知識點來看待。不以刷題進大廠為目的,而是以學習為目的。這裡的知識點會持續更新,目錄也會隨時進行調整。 ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...