前言

对于项目配置文件的读取和修改,.net 提供了ConfigurationManager(位于System.Configuration命名空间) 和WebConfigurationManager(位于System.Web.Configuration命名空间)两个类,能够很方便的操作项目的配置文件。另外,对于 Web 应用程序配置,建议使用 WebConfigurationManager 类,而不要使用 ConfigurationManager 类。

演示

下面是一个asp.net mvc5项目的项目配置文件

Web.config

 <?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20160513023153.mdf;Initial Catalog=aspnet-WebApplication1-20160513023153;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MoocEntities" connectionString="metadata=res://*/Models.MOOC.csdl|res://*/Models.MOOC.ssdl|res://*/Models.MOOC.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Mooc;user id=sa;password=aaaaaa;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>

获取与修改appSettings配置节点下的属性值

WebConfigurationManager提供了AppSettings属性,便于访问配置文件中appSettings节点下的元素的value值

下图为Web.config中要获取值的元素

编写如下代码,并在第27行打上断点调试

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;
using System.Text;
using System.Collections.Specialized;
using System.Collections;
using System.Diagnostics;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{ string version = WebConfigurationManager.AppSettings["webpages:Version"];
string enabled = WebConfigurationManager.AppSettings["webpages:Enabled"];
string clientValidationEnabled = WebConfigurationManager.AppSettings["ClientValidationEnabled"];
string unobtrusiveJavaScriptEnabled = WebConfigurationManager.AppSettings["UnobtrusiveJavaScriptEnabled"];
Debug.WriteLine("配置信息如下");
Debug.WriteLine(version);
Debug.WriteLine(enabled);
Debug.WriteLine(clientValidationEnabled);
Debug.WriteLine(unobtrusiveJavaScriptEnabled);
return Content("");
} }
}

调试模式“输出”窗口

以WebConfigurationManager.AppSettings["ClientValidationEnabled"]="要修改的值" 可直接修改值

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;
using System.Text;
using System.Collections.Specialized;
using System.Collections;
using System.Diagnostics;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{ string version = WebConfigurationManager.AppSettings["webpages:Version"];
string enabled = WebConfigurationManager.AppSettings["webpages:Enabled"];
WebConfigurationManager.AppSettings["ClientValidationEnabled"]="aaaaaaaaaaaaaaaaaaaaa";//动态修改value
string clientValidationEnabled = WebConfigurationManager.AppSettings["ClientValidationEnabled"];
string unobtrusiveJavaScriptEnabled = WebConfigurationManager.AppSettings["UnobtrusiveJavaScriptEnabled"];
Debug.WriteLine("配置信息如下");
Debug.WriteLine(version);
Debug.WriteLine(enabled);
Debug.WriteLine(clientValidationEnabled);
Debug.WriteLine(unobtrusiveJavaScriptEnabled);
return Content("");
} }
}

调试输出

连接字符串修改

 /*获取数据库连接字符串*/
string moocConnection = WebConfigurationManager.ConnectionStrings["MoocEntities"].ConnectionString;
Debug.WriteLine("连接字符串如下:");//打印
Debug.WriteLine(moocConnection);//打印

未完待续-----

C#操作项目配置文件的更多相关文章

  1. springmvc 项目完整示例02 项目创建-eclipse创建动态web项目 配置文件 junit单元测试

    包结构 所需要的jar包直接拷贝到lib目录下 然后选定 build path 之后开始写项目代码 配置文件 ApplicationContext.xml <?xml version=" ...

  2. Python中操作ini配置文件

    这篇博客我主要想总结一下python中的ini文件的使用,最近在写python操作mysql数据库,那么作为测试人员测试的环境包括(测试环境,UAT环境,生产环境)每次需要连接数据库的ip,端口,都会 ...

  3. 微信小游戏 项目配置文件 project.config.json

    一.项目配置文件project.config.json 小程序开发者工具在每个项目的根目录都会生成一个 project.config.json,在工具上做的任何配置都会写入到这个文件,当重新安装工具或 ...

  4. C#操作XML配置文件

    代码为C#操作xml配置文件的范例类,函数SetValue用于向配置文件写入一个值,GetValue用于根据Key获取相应值。这种方法的配置文件不需要手动创建,程序在运行后会自动处理创建。 注意:1. ...

  5. spring-boot-plus项目配置文件(四)

    spring-boot-plus项目配置文件 配置文件说明 配置说明 项目中配置文件主要使用yml格式 配置文件位置:spring-boot-plus\src\main\resources\confi ...

  6. springMVC项目配置文件

    一.springMVC项目配置文件 1.web.xml文件全局配置 <servlet> <servlet-name> dispatcher </servlet-name& ...

  7. python pyyaml操作yaml配置文件

    在测试工作中,可以使用yaml编写测试用例,执行测试用例时直接获取yaml中的用例数据进行测试(如:接口自动化测试) 1.什么是yaml 是一种可读的数据序列化语言,通常用于配置文件 非常简洁和强大, ...

  8. GIT·全局配置文件及项目配置文件

    阅文时长 | 0.03分钟 字数统计 | 48.8字符 主要内容 | 1.引言&背景 2.声明与参考资料 『GIT·全局配置文件及项目配置文件』 编写人 | SCscHero 编写时间 | 2 ...

  9. VC++/MFC操作ini配置文件详解

    在我们写的程序当中,总有一些配置信息需要保存下来,以便完成程序的功能,最简单的办法就是将这些信息写入INI文件中,程序初始化时再读入.具体应用如下: 一.将信息写入.INI文件中. 1.所用的WINA ...

随机推荐

  1. Ffmpeg和SDL如何同步音频

    ong> 同步音頻 现在我们已经有了一个比较像样的播放器.所以让我们看一下还有哪些零碎的东西没处理.上次,我们掩饰了一点同步问题,也就是同步音频到视频而不是其它的同步方式.我们将采用和视频一样的 ...

  2. 多线程中的lua同步问题

    最近写paintsnow::start时出现了一个非常麻烦的BUG,程序的Release版本大约每运行十几次就会有一次启动时崩溃(Debug版本还没崩溃过),崩溃点也不固定.经过简单分析之后,确定是线 ...

  3. 基于Vue 和 webpack的项目实现

    Vue.js 是一款极简的 mvvm 框架,如果让我用一个词来形容它,就是 “轻·巧” .如果用一句话来描述它,它能够集众多优秀逐流的前端框架之大成,但同时保持简单易用.废话不多说,来看几个例子: & ...

  4. Java使用默认浏览器打开指定URL

    直接贴代码: 方法一: Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://www.baidu.co ...

  5. Sql Server相关的性能计数器

    OS Memory and Paging 性能计数器: 1.Memory\Availability Mbytes   未使用的物理内存(非页面文件),通常情况下它应该大于100MB 2.Memory\ ...

  6. 【.NetRemoting-2】2015.09.17

    [Remoting架构] [1]是.NetFramework的一个重要组成 [2]框架的两个重要特性 [A]基本实现[B]可扩展/可定制 [各个组成部分] [1][客户端,客户端应用程序域] [组成] ...

  7. 从汇编看c++的虚拟继承以及其内存布局(一)

    先看第一种最简单的情形,所有类中没有任何虚函数的菱形继承. 下面是c++源码: class Top {//虚基类 public: int i; Top(int ii) { i = ii; } }; c ...

  8. JavaScript学习笔记:数组reduce()和reduceRight()方法

    很多时候需要累加数组项的得到一个值(比如说求和).如果你碰到一个类似的问题,你想到的方法是什么呢?会不会和我一样,想到的就是使用for或while循环,对数组进行迭代,依次将他们的值加起来.比如: v ...

  9. 利用Azure Automation实现云端自动化运维(2)

      Azure automation的认证: 用户名和密码   在Azure的automation中使用Powershell可以管理当前订阅的资源,也可以管理不同订阅的资源,那么问题就来了,安全性如何 ...

  10. javascript事件设计模式

    JavaScript事件设计模式 http://plkong.iteye.com/blog/213543 http://www.docin.com/p-696665922.html