C#读写App.config文件 C#如何通过ConfigurationManager操作配置文件

来源:这里教程网 时间:2026-02-21 17:42:02 作者:

App.config 文件读取必须先添加引用和 using

直接调用

ConfigurationManager
会报“未找到类型或命名空间”的错误,因为这个类不在默认引用里。你需要手动添加
System.Configuration
程序集引用,并在代码顶部加
using System.Configuration;
。.NET Core / .NET 5+ 项目默认不支持
ConfigurationManager
,它只适用于传统的 .NET Framework(如 4.7.2、4.8)桌面应用。

appSettings 节点读写要区分 Get 和 Set 方法

ConfigurationManager.AppSettings
是只读的,不能直接赋值修改。想更新配置必须打开配置文件、获取可写节、修改后显式保存:

读取:
ConfigurationManager.AppSettings["MyKey"]
(返回
string
,键不存在时返回
null
写入:需通过
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
获取配置对象,再操作
appSettings.Settings["MyKey"].Value = "new value"
,最后调用
config.Save()
注意:
Save()
默认只写入用户配置(user.config),要写回 App.config 必须传
ConfigurationSaveMode.Modified
并设
config.SaveAs("App.config")
—— 但实际不推荐,因为运行时改 App.config 不生效,下次启动才读新值

自定义配置节需要声明 SectionHandler 类型

如果在 App.config 里写了

<configsections><section name="mySection" type="..."></section></configsections>
,但没配对的
type
实现类,运行时会抛
ConfigurationErrorsException
:“无法创建配置节处理程序”。你得自己写一个继承
ConfigurationSection
的类,例如:

public class MyConfigSection : ConfigurationSection
{
    [ConfigurationProperty("timeout", DefaultValue = 30)]
    public int Timeout => (int)this["timeout"];
}

然后在 App.config 中的

type
属性填完整类型名,比如
MyApp.MyConfigSection, MyApp
(含程序集名)。

部署后 App.config 重命名为 exe.config,路径别硬编码

发布后的配置文件不是叫

App.config
,而是
YourApp.exe.config
,放在输出目录下。不要用
File.ReadAllText("App.config")
这种方式读取 —— 它既找不到文件,也绕过了 .NET 的配置缓存机制。所有访问都应走
ConfigurationManager
API;若需手动编辑,路径应通过
AppDomain.CurrentDomain.BaseDirectory
拼接
Assembly.GetExecutingAssembly().GetName().Name + ".exe.config"
,但再次强调:运行时改它不会立刻生效。

真正容易被忽略的是:配置变更后,除非重启进程,否则

ConfigurationManager
缓存的值不会刷新 —— 即使你改了磁盘上的 .exe.config 文件并调用了
ConfigurationManager.RefreshSection("appSettings")
,某些旧版本框架仍有缓存 bug,最稳的方式仍是重启应用。

相关推荐