答案:C#中读写App.config需用ConfigurationManager读取,通过OpenExeConfiguration修改并保存。读取时直接访问AppSettings或ConnectionStrings;写入时需加载配置对象,修改后调用Save()并刷新。权限不足可能导致写入失败,建议用户级设置使用Properties.Settings.Default,避免直接修改App.config。自定义配置节可提升结构化与类型安全,适合复杂配置。

在C#中,读写
App.config
System.Configuration
ConfigurationManager
ConfigurationManager.AppSettings
要读写C#的
App.config
1. 读取配置
对于
App.config
<appSettings>
// 假设App.config中有 <add key="MySetting" value="Hello World" />
string mySettingValue = System.Configuration.ConfigurationManager.AppSettings["MySetting"];
Console.WriteLine($"读取到的配置:{mySettingValue}");
// 读取连接字符串
// 假设App.config中有 <connectionStrings> <add name="MyDb" connectionString="Data Source=..." providerName="System.Data.SqlClient" /> </connectionStrings>
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDb"]?.ConnectionString;
Console.WriteLine($"读取到的连接字符串:{connectionString}");ConfigurationManager
YourApp.exe.config
2. 写入/修改配置
直接通过
ConfigurationManager.AppSettings.Add()
ConfigurationManager.AppSettings.Set()
App.config
AppSettings
App.config
ConfigurationManager.OpenExeConfiguration()
AppSettingsSection
AppSettingsSection
Settings
Save()
ConfigurationManager.RefreshSection()
以下是一个修改或添加
<appSettings>
using System;
using System.Configuration; // 需要引用 System.Configuration
public class ConfigWriter
{
public static void UpdateAppSetting(string key, string value)
{
try
{
// 获取当前应用程序的配置对象
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// 获取或创建 appSettings 节
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
if (appSettings == null)
{
// 如果没有 appSettings 节,就创建一个
appSettings = new AppSettingsSection();
config.Sections.Add("appSettings", appSettings);
}
// 检查键是否存在,如果存在则修改,否则添加
if (appSettings.Settings[key] != null)
{
appSettings.Settings[key].Value = value;
Console.WriteLine($"配置项 '{key}' 已更新为 '{value}'。");
}
else
{
appSettings.Settings.Add(key, value);
Console.WriteLine($"配置项 '{key}' 已添加,值为 '{value}'。");
}
// 保存配置更改
config.Save(ConfigurationSaveMode.Modified);
// 强制重新加载 appSettings 节,使更改立即生效
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine("配置已成功保存并刷新。");
}
catch (ConfigurationErrorsException ex)
{
Console.WriteLine($"写入配置时发生错误: {ex.Message}");
// 进一步处理,例如日志记录
}
catch (Exception ex)
{
Console.WriteLine($"发生意外错误: {ex.Message}");
}
}
// 示例用法
public static void Main(string[] args)
{
// 假设 App.config 中有 <add key="TestKey" value="OldValue" />
Console.WriteLine($"修改前 TestKey: {ConfigurationManager.AppSettings["TestKey"]}");
UpdateAppSetting("TestKey", "NewValue_" + DateTime.Now.Ticks);
Console.WriteLine($"修改后 TestKey: {ConfigurationManager.AppSettings["TestKey"]}");
// 添加一个新键
Console.WriteLine($"添加前 NewKey: {ConfigurationManager.AppSettings["NewKey"]}");
UpdateAppSetting("NewKey", "SomeNewValue");
Console.WriteLine($"添加后 NewKey: {ConfigurationManager.AppSettings["NewKey"]}");
// 再次读取确认
Console.WriteLine($"最终 TestKey: {ConfigurationManager.AppSettings["TestKey"]}");
Console.WriteLine($"最终 NewKey: {ConfigurationManager.AppSettings["NewKey"]}");
}
}请注意,修改
App.config
说实话,我个人觉得很多人在刚接触C#配置时,都会下意识地去尝试
ConfigurationManager.AppSettings["key"] = "newValue";
App.config
App.config
[应用程序名].exe.config
.config
Access Denied
更深层次地看,
ConfigurationManager.AppSettings
Add
Set
.config
config.Save()
在我看来,这种设计是有道理的。它将应用程序的配置分为几个层次:
App.config
[AppName].exe.config
user.config
AppData
ApplicationSettingsBase
Custom XML Files
XmlDocument
所以,当你尝试修改
App.config
OpenExeConfiguration
Save
user.config
有时候,简单的键值对(
AppSettings
connectionStrings
AppSettings
自定义配置节的优势非常明显:
App.config
ConfigurationSection
ConfigurationElement
IsRequired
MinValue
MaxValue
举个例子: 假设我们要配置一个邮件发送服务,包括SMTP服务器地址、端口、用户名、密码和是否启用SSL。如果用
AppSettings
<appSettings> <add key="SmtpServer" value="smtp.example.com" /> <add key="SmtpPort" value="587" /> <add key="SmtpUsername" value="user@example.com" /> <add key="SmtpPassword" value="password" /> <add key="SmtpEnableSsl" value="true" /> </appSettings>
代码读取时:
string server = ConfigurationManager.AppSettings["SmtpServer"]; int port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]); // ... 还有很多类似的读取和转换
如果使用自定义配置节,它看起来会更优雅:
1. 定义配置类:
using System.Configuration;
// 定义一个配置节,对应 <mailSettings>
public class MailSettingsSection : ConfigurationSection
{
// 定义一个配置元素集合,对应 <accounts> 里面的多个 <add>
[ConfigurationProperty("accounts", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(MailAccountCollection), AddItemName = "add")]
public MailAccountCollection Accounts
{
get { return (MailAccountCollection)base["accounts"]; }
}
}
// 定义一个配置元素集合,包含多个 MailAccountElement
public class MailAccountCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new MailAccountElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MailAccountElement)element).Name;
}
public MailAccountElement this[int index]
{
get { return (MailAccountElement)BaseGet(index); }
}
public new MailAccountElement this[string name]
{
get { return (MailAccountElement)BaseGet(name); }
}
}
// 定义一个配置元素,对应 <add name="Default" ... />
public class MailAccountElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get { return (string)this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("server", IsRequired = true)]
public string Server
{
get { return (string)this["server"]; }
set { this["server"] = value; }
}
[ConfigurationProperty("port", DefaultValue = 25, IsRequired = false)]
[IntegerValidator(MinValue = 1, MaxValue = 65535)]
public int Port
{
get { return (int)this["port"]; }
set { this["port"] = value; }
}
[ConfigurationProperty("username", IsRequired = true)]
public string Username
{
get { return (string)this["username"]; }
set { this["username"] = value; }
}
[ConfigurationProperty("password", IsRequired = true)]
public string Password
{
get { return (string)this["password"]; }
set { this["password"] = value; }
}
[ConfigurationProperty("enableSsl", DefaultValue = false, IsRequired = false)]
public bool EnableSsl
{
get { return (bool)this["enableSsl"]; }
set { this["enableSsl"] = value; }
}
}2. 在App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="mailSettings" type="YourNamespace.MailSettingsSection, YourAssembly" />
</configSections>
<mailSettings>
<accounts>
<add name="Default" server="smtp.example.com" port="587" username="user@example.com" password="password123" enableSsl="true" />
<add name="Backup" server="backup.smtp.com" port="465" username="backup@example.com" password="password456" enableSsl="true" />
</accounts>
</mailSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>(注意:
YourNamespace.MailSettingsSection, YourAssembly
3. 代码中读取:
MailSettingsSection mailConfig = (MailSettingsSection)ConfigurationManager.GetSection("mailSettings");
if (mailConfig != null)
{
MailAccountElement defaultAccount = mailConfig.Accounts["Default"];
if (defaultAccount != null)
{
Console.WriteLine($"SMTP Server: {defaultAccount.Server}");
Console.WriteLine($"SMTP Port: {defaultAccount.Port}");
Console.WriteLine($"SMTP Username: {defaultAccount.Username}");
Console.WriteLine($"Enable SSL: {defaultAccount.EnableSsl}");
}
}你看,通过自定义配置节,我们不仅让配置文件的结构更清晰,代码在读取时也获得了强类型的好处,再也不用担心字符串转换错误了。这种方式对于管理复杂的、多层次的应用程序配置来说,简直是神器。
处理
App.config
App.config
明确App.config
.config
App.config
利用用户设置(User Settings): 这是最优雅、最符合Windows应用程序设计模式的方式。在Visual Studio中,项目属性里有一个“设置”选项卡,你可以定义各种类型的设置(字符串、整数、布尔等),并选择其作用域是“应用程序”还是“用户”。
App.config
user.config
Properties.Settings.Default
Properties.Settings.Default.MyUserSetting
Properties.Settings.Default.MyUserSetting = "NewValue"; Properties.Settings.Default.Save();
AppData
如果非要修改App.config
OpenExeConfiguration
Save
App.config
try-catch
ConfigurationErrorsException
IOException
App.config
以上就是C#的配置文件App.config应该如何读写?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号