在C#应用程序开发中,配置文件是存储程序运行时所需可变参数的常用方式,避免了将参数硬编码在代码中,方便后续调整和部署。最常见的配置文件是App.config(桌面应用)和Web.config(Web应用),两者的操作逻辑基本一致,本文以桌面应用的App.config为例展开讲解。

一、基础配置文件的创建与内置配置节使用
1.1 创建配置文件
在Visual Studio中创建C#桌面项目后,右键项目选择添加,新建项,找到应用程序配置文件,默认名称就是App.config,添加后文件内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>
1.2 使用内置的connectionStrings配置节
内置的connectionStrings配置节专门用来存储数据库连接字符串,我们添加对应的配置内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<connectionStrings>
<add name="DefaultDb" connectionString="Server=127.0.0.1;Database=TestDb;Uid=root;Pwd=123456;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
读取该配置需要引用System.Configuration命名空间,然后通过ConfigurationManager类获取,代码示例:
using System;
using System.Configuration;
namespace ConfigDemo
{
class Program
{
static void Main(string[] args)
{
// 读取connectionStrings配置
string connStr = ConfigurationManager.ConnectionStrings["DefaultDb"].ConnectionString;
Console.WriteLine("数据库连接字符串:{0}", connStr);
}
}
}
1.3 使用内置的appSettings配置节
appSettings配置节用来存储简单的键值对参数,添加配置如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<connectionStrings>
<add name="DefaultDb" connectionString="Server=127.0.0.1;Database=TestDb;Uid=root;Pwd=123456;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="MaxRetryCount" value="3" />
<add key="LogPath" value="D:Logs" />
</appSettings>
</configuration>
读取appSettings配置的代码示例:
using System;
using System.Configuration;
namespace ConfigDemo
{
class Program
{
static void Main(string[] args)
{
// 读取appSettings配置
string maxRetryCount = ConfigurationManager.AppSettings["MaxRetryCount"];
string logPath = ConfigurationManager.AppSettings["LogPath"];
Console.WriteLine("最大重试次数:{0},日志路径:{1}", maxRetryCount, logPath);
}
}
}
二、自定义配置节的开发
当内置配置节无法满足复杂的配置需求时,我们可以自定义配置节,比如需要配置多个具有相同结构的业务参数时,自定义配置节会更清晰。
2.1 定义配置节对应的类
首先定义配置节的处理类,需要继承ConfigurationSection,代码示例:
using System.Configuration;
namespace ConfigDemo
{
// 自定义配置节类
public class ServiceConfigSection : ConfigurationSection
{
// 定义配置元素的集合属性
[ConfigurationProperty("services")]
public ServiceElementCollection Services
{
get { return (ServiceElementCollection)this["services"]; }
}
}
// 配置元素类
public class ServiceElement : ConfigurationElement
{
// 服务名称属性
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
// 服务地址属性
[ConfigurationProperty("url", IsRequired = true)]
public string Url
{
get { return (string)this["url"]; }
set { this["url"] = value; }
}
// 服务超时时间属性
[ConfigurationProperty("timeout", DefaultValue = 30)]
public int Timeout
{
get { return (int)this["timeout"]; }
set { this["timeout"] = value; }
}
}
// 配置元素集合类
public class ServiceElementCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new ServiceElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ServiceElement)element).Name;
}
}
}
2.2 在配置文件中注册自定义配置节
需要在configuration标签下添加configSections节点,注册自定义配置节,然后添加自定义配置内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="serviceConfig" type="ConfigDemo.ServiceConfigSection, ConfigDemo" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<connectionStrings>
<add name="DefaultDb" connectionString="Server=127.0.0.1;Database=TestDb;Uid=root;Pwd=123456;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="MaxRetryCount" value="3" />
<add key="LogPath" value="D:Logs" />
</appSettings>
<serviceConfig>
<services>
<add name="UserService" url="http://127.0.0.1:8080/user" timeout="20" />
<add name="OrderService" url="http://127.0.0.1:8080/order" timeout="30" />
</services>
</serviceConfig>
</configuration>
注意type属性的格式是命名空间.类名, 程序集名称,如果程序集名称和命名空间不一致需要对应调整。
2.3 读取自定义配置节
读取自定义配置节的代码示例:
using System;
using System.Configuration;
namespace ConfigDemo
{
class Program
{
static void Main(string[] args)
{
// 读取自定义配置节
ServiceConfigSection serviceConfig = (ServiceConfigSection)ConfigurationManager.GetSection("serviceConfig");
if (serviceConfig != null)
{
foreach (ServiceElement service in serviceConfig.Services)
{
Console.WriteLine("服务名称:{0},地址:{1},超时时间:{2}秒", service.Name, service.Url, service.Timeout);
}
}
}
}
}
三、配置文件的修改与注意事项
如果需要动态修改配置文件的内容,可以通过Configuration对象实现,示例代码如下:
using System;
using System.Configuration;
namespace ConfigDemo
{
class Program
{
static void Main(string[] args)
{
// 打开当前应用程序的配置文件
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 修改appSettings中的配置
if (config.AppSettings.Settings["MaxRetryCount"] != null)
{
config.AppSettings.Settings["MaxRetryCount"].Value = "5";
}
else
{
config.AppSettings.Settings.Add("MaxRetryCount", "5");
}
// 保存修改
config.Save(ConfigurationSaveMode.Modified);
// 刷新配置,让修改立即生效
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine("配置修改完成");
}
}
}
注意事项
- 修改配置文件后,程序运行时的配置文件名称会变成
程序名.exe.config,位于程序输出目录下,直接修改项目中的App.config不会直接影响运行时的配置,需要重新生成项目。 - 读取配置时如果对应的配置项不存在,
ConfigurationManager.AppSettings["key"]会返回null,需要做空值判断避免异常。 - 自定义配置节的类需要是公共的,且配置属性需要标记
ConfigurationProperty特性,才能正确映射配置文件中的内容。
C#配置文件App.configConfigurationManager自定义配置节修改时间:2026-06-13 22:03:46