跳转到主要内容
杨月昌的软件博客
返回

WPF 程序中的 App.Config 文件读写操作详解

一、 App.Config 文件的作用与结构

在 WPF 应用程序中,App.Config 是管理静态配置的标准方式。它本质上是一个 XML 文件,编译后会重命名为 你的程序名.exe.config 并存放在运行目录下。

常见的结构包含 appSettings(简单键值对)和 connectionStrings(数据库连接字符串):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ServerIp" value="192.168.1.100"/>
    <add key="UnitWidth" value="1920"/>
  </appSettings>
  
  <connectionStrings>
    <add name="DefaultDb" connectionString="Server=.;Database=Test;Integrated Security=True;"/>
  </connectionStrings>
</configuration>

二、 基础操作:使用 ConfigurationManager

在 WPF 中操作配置,首先需要在项目中引用 System.Configuration 程序集。

1. 读取配置

不要使用过时的 ConfigurationSettings。现代开发中应统一使用 ConfigurationManager

using System.Configuration;

// 读取 appSettings
string ip = ConfigurationManager.AppSettings["ServerIp"];

// 读取 connectionStrings
string conn = ConfigurationManager.ConnectionStrings["DefaultDb"].ConnectionString;

2. 写入与更新配置

写入操作通常用于软件的“设置”界面。需要注意:写入操作会直接修改磁盘上的 .exe.config 文件

public static void UpdateSetting(string key, string value)
{
    // 打开配置文件
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
    // 如果存在则修改,不存在则添加
    if (config.AppSettings.Settings[key] != null)
    {
        config.AppSettings.Settings[key].Value = value;
    }
    else
    {
        config.AppSettings.Settings.Add(key, value);
    }
    
    // 保存并强制刷新缓存,确保下次读取到的是最新值
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
}

三、 进阶:使用 XmlDocument 处理自定义节点

当配置文件包含复杂的自定义节点(如 easentityFramework)时,标准的 ConfigurationManager 可能无法直接修改。此时我们可以将 .config 作为纯 XML 文件进行操作。

示例:动态解析并修改嵌套属性

假设我们需要修改深度嵌套的 Url 属性:

public void UpdateCustomSection(string newIp)
{
    // 获取编译后的配置文件路径
    string path = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
    
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(path);
    
    // 定位到自定义节点
    XmlNode node = xmlDoc.SelectSingleNode("configuration/eas/objects/object/property[@name='Url']");
    
    if (node != null)
    {
        // 假设原值为 socket.tcp://127.0.0.1:1000/
        string oldValue = node.Attributes["value"].Value;
        // 执行字符串替换或重新构建
        node.Attributes["value"].Value = $"socket.tcp://{newIp}:1000/";
        
        xmlDoc.Save(path);
        ConfigurationManager.RefreshSection("eas"); // 刷新自定义段
    }
}

四、 开发中的常见坑点(注意事项)

  1. 调试环境 vs 运行环境
  1. 权限问题
  1. 类型转换

五、 总结

App.Config 是 WPF 存储静态配置的基石。对于简单的参数,使用 ConfigurationManager 即可高效处理;对于复杂的第三方框架节点,灵活运用 XmlDocument 能解决绝大多数问题。



上一篇
自注意力机制(Self-Attention)深度解构:从2017到2026的十年演进
下一篇
优化代理池:如何解决 Redis 中的代理 IP 重复与质量管理问题