在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
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...