ホームページ  >  記事  >  バックエンド開発  >  ASP.NETでのConfigファイルの読み書きについての説明

ASP.NETでのConfigファイルの読み書きについての説明

ringa_lee
ringa_leeオリジナル
2017-10-15 10:09:081546ブラウズ

通常、.NET 開発プロセスでは、構成ファイルと XML ファイルという 2 種類の構成ファイルを使用します。次の記事では、主に ASP.NET での構成ファイルの読み取りと書き込みに関する関連情報を紹介します。記事ではサンプルコードを詳しく紹介していますので、必要な方はぜひ参考にしてみてください。

この記事では、主に 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")

例を書く


rrリー

以上がASP.NETでのConfigファイルの読み書きについての説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。