C#程序中访问配置文件
在C#编程中,有时候会用到配置文件,那么该如何在程序中获取或修改配置文件中的相关数据呢?下面采用一个简单的C#控制台程序来说明。
新建一个C#控制台程序,打开“解决方案资源管理器”,如下图:
可以看到里面没有配置文件,下面使用修改.net的版本来将其调出来。选中工程,单击右键,选择属性。
此时配置文件出来了。按照下图添加配置信息:
好了,现在我们就添加代码来访问这些信息。
/// <summary>
/// 在配置信息中根据指定的键获取值。
/// </summary>
/// <param name="key">指定的键。</param>
/// <returns></returns>
public static string GetConfigurationValue(string key)
{
return ConfigurationManager.AppSettings[key];
}
/// <summary>
/// 在配置信息中修改指定键的值。
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void SetConfigurationValue(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}
添加代码后,会发现程序报错,此时我们应该添加一个dll的引用,并在文件中加入
using System.Configuration;
在Main函数中添加代码
static void Main(string[] args)
{
Console.WriteLine(GetConfigurationValue("id"));
Console.WriteLine(GetConfigurationValue("sex"));
Console.WriteLine(GetConfigurationValue("age"));
SetConfigurationValue("id", "007");
SetConfigurationValue("sex", "女");
SetConfigurationValue("age", "26");
Console.WriteLine();
Console.WriteLine(GetConfigurationValue("id"));
Console.WriteLine(GetConfigurationValue("sex"));
Console.WriteLine(GetConfigurationValue("age"));
}
运行结果如下: