说到配置文件大家首先想到的就是app.config或者web.config。今天就开始给大家分享怎么样管理配置文件,说是管理,其实就是读和写。今天先给大家介绍最常见的*.config配置文件的读和写。
首先,如果我们想在app.config文件中保存一个变量的时候,我们会这样写:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DateTime" value="2015/10/21 16:55:00"/>
</appSettings>
</configuration>
编写我们的读和写的方法
<span> </span>///<summary>
///返回*.exe.config文件中appSettings配置节的value项
///</summary>
///<param name="strKey"></param>
///<returns></returns>
private static string GetAppConfig(string strKey)
{
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == strKey)
{
return ConfigurationManager.AppSettings[strKey];
}
}
return null;
}
///<summary>
///在*.exe.config文件中appSettings配置节增加一对键、值对
///</summary>
///<param name="Key"></param>
///<param name="Value"></param>
private static void UpdateAppConfig(string Key, string Value)
{
bool isModified = false;
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == Key)
{
isModified = true;
}
}
// 打开配置文件
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 如果配置文件中存在该节点,则先移除原来的节点然后再添加该节点
if (isModified)
{
config.AppSettings.Settings.Remove(Key);
}
//添加新节点
config.AppSettings.Settings.Add(Key, Value);
//保存配置文件
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
调用我们编写的读和写的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetAppConfig("DateTime"));
//修改DateTime的值
UpdateAppConfig("DateTime", DateTime.Now.ToString());
//添加hehe,值为呵呵
UpdateAppConfig("hehe", "呵呵");
Console.WriteLine(GetAppConfig("DateTime"));
Console.WriteLine(GetAppConfig("hehe"));
}
}
}
咱们可以看见,咱们编写的读和写的方法能够正常运行,但是再看看我们的app.config文件,里面的内容并没有改变,这是因为咱们在写的方法中的这一行代码
config.Save(ConfigurationSaveMode.Modified);
Save的方法能保存我们写的值,但不会保存在文件中。如果我们用下面的代码
config.SaveAs("C:/Users/焱/Desktop/ConsoleApplication2/ConsoleApplication2/App.config", ConfigurationSaveMode.Full);
使用SaveAs的方法就能够把咱们写入的内容写入到文件中。