.config文件与.xml文件的关系

首先说一下.config,一般新建项目自带配置文件无非app.config或者web.config

1、前者一般是新建winform或者控制台等,而后者是新建web项目时创建

2、前者用System.Configuration.ConfigurationManager对文档就行管理,而后者用System.Web.Configuration.WebConfigurationManager,当然web项目使用ConfigurationManager并没有错,但微软建议web项目使用WebConfigurationManager

 

客户端应用程序使用System.Configuration.ConfigurationManager操作.config文件

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace app.config文件操作
{
class Program
{
static void Main(string[] args)
{
//读操作
string value1=ConfigurationManager.AppSettings["name"];
string value2=ConfigurationManager.AppSettings.Get("name");

//写操作
ExeConfigurationFileMap filemap = new ExeConfigurationFileMap();
string path = Directory.GetCurrentDirectory();
filemap.ExeConfigFilename = path + "\\App.config";//配置文件路径,为了代码简练此处让App.config输出到debug目录下
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(filemap, ConfigurationUserLevel.None);
//修改key为name的value
config.AppSettings.Settings["name"].Value = "曹操";
//在appsetings节点下新增一个add标签,key为age,value为23
config.AppSettings.Settings.Add("age", "23");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
}
}

web应用程序使用System.Web.Configuration.WebConfigurationManager操作.config文件

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;

namespace web.config文件操作.Controllers
{
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
appSection.Settings["name"].Value = "李四";
appSection.Settings.Add("age", "23");
config.Save();
return View();
}
}
}

 

把.config知识普及了一下

接下来说下.config与.xml区别,其实打个比方把xml就相当于文字,而config呢就相当于规范化后的文字比如写文章段落首行缩进等

转载于:https://www.cnblogs.com/nanjingcaiyong/p/6308922.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值