.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呢就相当于规范化后的文字比如写文章段落首行缩进等

posted @ 2017-01-19 22:16  南京夜空中最亮的星  阅读(1645)  评论(0编辑  收藏  举报