首頁  >  文章  >  後端開發  >  有關ASP.NET中Config檔案的讀寫講解

有關ASP.NET中Config檔案的讀寫講解

ringa_lee
ringa_lee原創
2017-10-15 10:09:081545瀏覽

通常我們在.NET開發過程中,會接觸二種類型的設定檔:config文件,xml文件,以下這篇文章主要給大家介紹了關於ASP.NET中Config文件讀寫的相關資料,文中透過範例程式碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。

本文主要為大家介紹了關於ASP.NET中Config讀寫範例的相關內容,分享出來供大家參考學習,話不多說,來一起看看詳細的介紹吧。

方法如下:

如果是WinForm程序,需要加入參考:

  • System. ServiceModel

  • System.Configuration

#App.config


##

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appSettings>
 <add key="testkey" value="0"></add>
 </appSettings>
</configuration>

NetUtilityLib


using System.Configuration;
namespace pcauto
{
 public static class ConfigHelper
 { 
  ///<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;
  }
  ///<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");
  }  
 }
}

讀取範例

##

ConfigHelper.GetAppConfig("testkey")

寫入範例

ConfigHelper.UpdateAppConfig("testkey", "abc");

以上是有關ASP.NET中Config檔案的讀寫講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn