C#应用的配置系统

软件在不同的运行环境或面对不同的用户需求时,肯恩更需要不同的参数设置。如果将其硬编码到代码中,每次修改都需要重新编译代码,效率低且容易出错;配置文件集中管理可变参数,只需要修改配置文件就能调整软件行为,极大提升软件的灵活度和可维护性。

.NET支持多种配置文件系统,使用较多的是传统的App.config和JSON文件,本文对它们进行简要介绍。

App.config

总的来说,App.config配置文件非常简单易用,同时支持属性读取和修改,对于一般项目已经足够。但这种方式实现多级属性较为复杂,在这方面不及JSON配置文件。

添加App.config配置文件

创建基于.NET Framework的项目时,会自动添加App.config配置文件,当然也可以手动添加,如下图所示:

定义配置文件

App.config文件内置一些常用的Section,包括appSettings、connectionStrings两种最常用的Section,前者表示程序配置信息,后者表示数据库连接字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="set1" value="hello"/>
<add key="set2" value="world"/>
<add key="set3" value="lihao"/>
<add key="set4" value="liruohan"/>
</appSettings>

<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>

配置信息读取

通过Configuration.AppSettings可以拿到appSettings节,其Settings属性是一个字典数据结构,里面包含了所有的配置数据,可以获取、删除、新增。

ConfigurationManager有两种打开配置文件的方法:OpenExeConfiguration()OpenMappedExeConfiguration(),后者比较灵活,可以打开制定的配置文件,前者打开默认的配置文件。

项目生成时,App.config文件会自动复制到生成目录,名称编程[exe名].Config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static class AppConfig {
private static Configuration _config;

static AppConfig() {
_config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}

public static string Get(string key) {
string value = null;
if (_config.AppSettings.Settings.AllKeys.Contains(key)) {
value = _config.AppSettings.Settings[key].Value;
}
return string.IsNullOrWhiteSpace(value) ? null : value;
}

public static bool Set(string key, string value) {
if (_config.AppSettings.Settings.AllKeys.Contains(key)) {
_config.AppSettings.Settings[key].Value = value;
_config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(_config.AppSettings.SectionInformation.Name);
return true;
}
return false;
}
}

调用

1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args) {
Console.WriteLine(AppConfig.Get("set1"));
Console.WriteLine(AppConfig.Get("set2"));
Console.WriteLine(AppConfig.Get("set3"));
Console.WriteLine(AppConfig.Get("set4"));

AppConfig.Set("set2", "woshilihao");
AppConfig.Set("set3", "woshilihao");

Console.ReadKey();
}

JSON

对于.NET项目,推荐使用Json配置文件,原因主要有以下几点:

  • JSON文件轻量、格式易读、适合表示复杂的数据结构。
  • JSON格式更为通用,跨平台支持较好。
  • 可与环境变量结合使用,允许在不同环境中动态覆盖配置值,而无需修改文件本身。
  • 提供强大的解析库,轻松加载和解析JSON文件,无需手动解析。
  • 支持动态更新。

定义配置文件

1
2
3
4
5
6
7
8
9
10
{
"AppSettings": {
"AppName": "MyApplication",
"Version": "1.0.0",
"Author": {
"Name": "LiHao",
"Motto": "Programming"
}
}
}

以普通方式读取

1
2
3
4
5
6
7
8
9
10
11
12
static void Main(string[] args) {
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var config = builder.Build();

Console.WriteLine(config["AppSettings:AppName"]);
Console.WriteLine(config["AppSettings:Version"]);
Console.WriteLine(config["AppSettings:Author:Name"]);

Console.ReadKey();
}

将配置绑定到类读取

(1)创建类

1
2
3
4
5
6
7
8
9
10
public class AppSettings {
public string AppName { get; set; }
public string Version { get; set; }
public Author Author { get; set; }
}

public class Author {
public string Name { get; set; }
public string Motto { get; set; }
}

(2)绑定并读取

可以将JSON中的某个节绑定到对象,默认是整个配置文件。这种方式不需要用户手动进行数据类型转换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static void Main(string[] args) {
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();

var appSettings = config.GetSection("AppSettings").Get<AppSettings>();

Console.WriteLine(appSettings.AppName);
Console.WriteLine(appSettings.Version);
Console.WriteLine(appSettings.Author.Name);
Console.WriteLine(appSettings.Author.Motto);

Console.ReadKey();
}

修改JSON配置文件

推荐使用System.Text.Json.Nodes库,可以轻松修改JSON的节点值,而不借用JSON文件序列化方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
static void Main(string[] args) {
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();

Console.WriteLine(config["AppSettings:AppName"]);

// 修改配置文件
var jsonText = File.ReadAllText("appsettings.json");
var jsonNode = JsonNode.Parse(jsonText);
jsonNode["AppSettings"]["AppName2"] = "lihao3";
File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(),"appsettings.json"),
jsonNode.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
config.Reload();

Console.WriteLine(config["AppSettings:AppName"]);

Console.ReadKey();
}
  • JSON配置文件修改后,需要调用Reload()函数重新加载。
  • 重新加载后,可以通过普通方式访问最新的属性值;但如果使用对象映射的方式,需要重新映射。

最佳方式

  • 如果只使用简单的配置项,使用App.config即可,无论是读取或者修改,都很方便。
  • 如果使用复杂的多级配置项,JSON是更好的选择,读取非常方便,修改操作稍微复杂些。
  • 如果需要修改JSON配置项,首推System.Text.Json.Nodes库。

(转载本站文章请注明作者和出处lihaohello.top,请勿用于任何商业用途)

评论