• .Net2.0 使用ConfigurationManager读写配置文件


     .net1.1中如果需要灵活的操作和读写配置文件并不是十分方便,一般都会在项目中封装一个配置文件管理类来进行读写操作。而在.net2.0中使用ConfigurationManagerWebConfigurationManager 类可以很好的管理配置文件,ConfigurationManager类在System.Configuration中,WebConfigurationManager在System.Web.Configuration中。根据MSDN的解释,对于 Web 应用程序配置,建议使用 System.Web.Configuration.WebConfigurationManager 类,而不要使用 System.Configuration.ConfigurationManager 类。

     

    下面我给出一个简单的例子说明如何使用WebConfigurationManager操作配置文件:
           //打开配置文件
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            
    //获取appSettings节点
            AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
            
    //在appSettings节点中添加元素
            appSection.Settings.Add("addkey1""key1's value");
            appSection.Settings.Add(
    "addkey2""key2's value");
            config.Save();


    运行代码之后可以看见配置文件中的改变:

    <appSettings>
      
    <add key="addkey1" value="key1's value" />
      
    <add key="addkey2" value="key2's value" />
    </appSettings>

    修改和删除节点或属性也非常方便:

           //打开配置文件
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            
    //获取appSettings节点
            AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
            
    //删除appSettings节点中的元素
            appSection.Settings.Remove("addkey1");
            
    //修改appSettings节点中的元素
            appSection.Settings["addkey2"].Value = "Modify key2's value";
            config.Save();

    配置文件:
    <appSettings>
       
    <add key="addkey2" value="Modify key2's value" />
     
    </appSettings>

    参考:http://msdn2.microsoft.com/en-us/library/ms228060.aspx
  • 相关阅读:
    使用git pull文件时和本地文件冲突怎么办?
    Git回滚代码到某个commit
    PHP如何在页面中原样输出HTML代码
    git 创建本地分支、提交到远程分支
    php mysqli扩展之预处理
    htmlspecialchars() 函数过滤XSS的问题
    PHP json_encode里面经常用到的 JSON_UNESCAPED_UNICODE和JSON_UNESCAPED_SLASHES
    javascript学习笔记——Array
    javascript学习笔记——Object
    javascript的底层实现学习总结
  • 原文地址:https://www.cnblogs.com/todd/p/1245617.html
Copyright © 2020-2023  润新知