C# app.config文件配置和修改


    很多時候我們需要對系統的.config文件進度讀寫操作,例如:系統初始化的參數的更改、系統參數的改變都需要更新到配置文件。

    首先我們有必要了解一下app.config、exe.config和vshost.exe.config作用和區別:

    vshost.exe.config是程序運行時的配置文本,exe.config是程序運行后會復制到vshost.exe.config,app.config是在vshost.exe.config和exe.config沒有情況起作用,從app.config復制到exe.config再復制到vshost.exe.config。vshost.exe.config和exe.config會自動創建內容跟app.config一樣。了解過這些其實寫配置文件都是寫到exe.config文件中了,app.config不會變化。網上也有許多關於配置文件的讀寫操作,也是借鑒了多位前輩的經驗自己總結的一些比較常用的讀寫操作。廢話不多說,直接上主題:

  1. appSetting節點
     1           /// <summary>
     2          /// 修改AppSettings中配置
     3          /// </summary>
     4          /// <param name="key">key值</param>
     5          /// <param name="value">相應值</param>
     6          public static bool SetConfigValue(string key, string value)
     7          {
     8              try
     9              {
    10                  Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    11                  if (config.AppSettings.Settings[key] != null)
    12                      config.AppSettings.Settings[key].Value = value;
    13                  else
    14                      config.AppSettings.Settings.Add(key, value);
    15                  config.Save(ConfigurationSaveMode.Modified);
    16                  ConfigurationManager.RefreshSection("appSettings");
    17                  return true;
    18              }
    19              catch
    20              {
    21                  return false;
    22              }
    23          }
    修改或新增AppSetting節點

     

     1         /// <summary>
     2         /// 獲取AppSettings中某一節點值
     3         /// </summary>
     4         /// <param name="key"></param>
     5         public static string GetConfigValue(string key)
     6         {
     7                 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     8                 if (config.AppSettings.Settings[key] != null)
     9                      return  config.AppSettings.Settings[key].Value;
    10                 else
    11                   
    12                 return string.Empty;
    13         }    
    獲取AppSetting節點值

     

  2. ConnectionStrings節點

     1         /// <summary>
     2         /// 獲取連接節點值
     3         /// </summary>
     4         /// <param name="key"></param>
     5         /// <returns></returns>
     6         public static string GetConnectionValue(string key)
     7         {
     8             if (ConfigurationManager.ConnectionStrings[key] != null)
     9                 return ConfigurationManager.ConnectionStrings[key].ConnectionString;
    10             return string.Empty;
    11         }    
    獲取ConnectionStrings節點值  
     
     1  public static void UpdateConnectionStringsConfig(string key, string conString)
     2         {
     3             bool isModified = false;    //記錄該連接串是否已經存在 
     4             if (ConfigurationManager.ConnectionStrings[key] != null)
     5             {
     6                 isModified = true;
     7             }
     8             //新建一個連接字符串實例 
     9             ConnectionStringSettings mySettings = new ConnectionStringSettings(key, conString);
    10 
    11             // 打開可執行的配置文件*.exe.config 
    12             Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    13 
    14             // 如果連接串已存在,首先刪除它 
    15             if (isModified)
    16             {
    17                 config.ConnectionStrings.ConnectionStrings.Remove(key);
    18             }
    19             // 將新的連接串添加到配置文件中. 
    20             config.ConnectionStrings.ConnectionStrings.Add(mySettings);
    21             // 保存對配置文件所作的更改 
    22             config.Save(ConfigurationSaveMode.Modified);
    23             // 強制重新載入配置文件的ConnectionStrings配置節  
    24             ConfigurationManager.RefreshSection("connectionStrings");
    25         }
    修改或新增ConnectionStrings節點

     

  3. System.ServiceModel節點

     1         /// <summary>
     2         /// 讀取EndpointAddress
     3         /// </summary>
     4         /// <param name="endpointName"></param>
     5         /// <returns></returns>
     6         public static string GetEndpointClientAddress(string endpointName)
     7         {
     8             ClientSection clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
     9             foreach (ChannelEndpointElement item in clientSection.Endpoints)
    10             {
    11                 if (item.Name == endpointName)
    12                     return item.Address.ToString();
    13             }
    14             return string.Empty;
    15         }
    16 
    17 
    18         /// <summary>
    19         /// 設置EndpointAddress
    20         /// </summary>
    21         /// <param name="endpointName"></param>
    22         /// <param name="address"></param>
    23         public static bool SetEndpointClientAddress(string endpointName, string address)
    24         {
    25             try
    26             {
    27                 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    28                 ClientSection clientSection = config.GetSection("system.serviceModel/client") as ClientSection;
    29                 foreach (ChannelEndpointElement item in clientSection.Endpoints)
    30                 {
    31                     if (item.Name != endpointName)
    32                         continue;
    33                     item.Address = new Uri(address);
    34                     break;
    35                 }
    36                 config.Save(ConfigurationSaveMode.Modified);
    37                 ConfigurationManager.RefreshSection("system.serviceModel");
    38                 return true;
    39             }
    40             catch (Exception ex)
    41             {
    42                 return false;
    43             }
    44 
    45         }
    客戶端Client的Endpoint
     
    服務端Service的Address

     

     

     對與配置文件的修改有些可能會覺得直接操作config文件對安全性來說代價太高了,這種情況下就需要個人取決一下可以使用將appconfig段放到獨立的config文件中,以XML的方式進行修改,並可以避免應用程序重啟的問題。

     簡單的再說一下放到獨立文件的操作

      

     剩下的就是對xml的操作

      

      
 1              string ConnectConfigPath = AppData.StartupPath + "\\Config\\DaoConfig.xml";//獲取配置文件路徑
 2 
 3                 //向DaoConfig里添加節點
 4                 XmlDocument xmlDoc = new XmlDocument();
 5                 xmlDoc.Load(ConnectConfigPath);
 6                 XmlNode xmldocSelect = xmlDoc.SelectSingleNode("/DaoConfig[1]");
 7 
 8                 xmldocSelect.RemoveAll();//刪除當前節點的所有子節點
 9 
10                 //添加test節點
11                 XmlElement Account = xmlDoc.CreateElement("test");
12                 Account.InnerText = "對應的值";
13                 xmldocSelect.AppendChild(Account);
14 
15 
16                 xmlDoc.Save(ConnectConfigPath);    
Dao.config文件新增節點的操作

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM