• C# 应用程序配置文件App.Config和web.config


    应用程序配置文件,对于asp.net是 web.config,对于WINFORM程序是 App.Config(ExeName.exe.config)。

    配置文件,对于程序本身来说,就是基础和依据,其本质是一个xml文件。

    对于配置文件的操作,从.NET 2.0 开始,就非常方便了,提供了 System [.Web] .Configuration 这个管理功能的NameSpace,要使用它,需要添加对 System.configuration.dll的引用。

    我们以最常见的 AppSettings 小节来作为例子:

    假设有如下的配置文件内容:

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

      <appSettings>

        <add key="y" value="this is Y"/>

      </appSettings>

    </configuration>

    一、ASP.NET

    1.命名空间

      对于ASP.NET 程序, 使用 System.Web.Configuration.WebConfigurationManager;

    2.读取

      
      System.Web.Configuration.WebConfigurationManager.AppSettings[“y”];

    3.添加

    需要有写权限:

      

    Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 
    
    AppSettingsSection app = config.AppSettings; 
    
    app.Settings.Add("x", "this is X"); 
    
    config.Save(ConfigurationSaveMode.Modified);

    4.修改

    Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 
    
    AppSettingsSection app = config.AppSettings; //app.Settings.Add("x", "this is X"); 
    
    app.Settings["x"].Value = "this is not Y"; 
    
    config.Save(ConfigurationSaveMode.Modified);
    
     

    5.删除

    Configuration config = WebConfigurationManager.OpenWebConfiguration(null); 
    
    AppSettingsSection app = config.AppSettings;
    
    app.Settings.Remove("x");
    
    config.Save(ConfigurationSaveMode.Modified);

    .

    二、WINFORM / CONSOLE

    1.命名空间

      对于WINFORM程序,使用 System.Configuration.ConfigurationManager;

    2.读取

      System.Configuration.ConfigurationManager.AppSettings[“y”];

    3.添加

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    
    AppSettingsSection app = config.AppSettings; 
    
    app.Settings.Add("x", "this is X"); 
    
    config.Save(ConfigurationSaveMode.Modified);

    4.修改

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    
    AppSettingsSection app = config.AppSettings; //app.Settings.Add("x", "this is X"); 
    
    app.Settings["x"].Value = "this is not Y"; 
    
    config.Save(ConfigurationSaveMode.Modified);
    
    ConfigurationManager.RefreshSection("appSettings");// 刷新命名节,在下次检索它时将从磁盘重新读取它。记住应用程序要刷新节点
    

    PS: 修改后,App.config文件的x节点没有更改,而是exe.config的配置更改,读取正常

    5.删除

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    
    AppSettingsSection app = config.AppSettings; 
    
    app.Settings.Remove("x"); 
    
    config.Save(ConfigurationSaveMode.Modified);
  • 相关阅读:
    [公告]博客园准备建立SharePoint团队
    [公告]新增三款Skin
    又新增三款Skin
    一个不错的计数器
    [公告]新建新手区
    2005年1月16日 IT Pro 俱乐部活动纪实
    [好消息]祝成科技.微软公司.博客园联合打造IT俱乐部
    [公告]SharePoint团队正式成立
    SharePoint文档库存在问题
    [活动]2004年计算机图书评选
  • 原文地址:https://www.cnblogs.com/xcsn/p/4543400.html
Copyright © 2020-2023  润新知