当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET中Config文件的读写示例

ASP.NET中Config文件的读写示例

2017年08月16日  | 移动技术网IT编程  | 我要评论

重生小凤凰的童养夫,雾气缭绕的幽魂灯笼,手机美文

本文主要给大家介绍了关于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");

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网