C#读写Config配置文件



在C#中,通常使用XML或JSON格式的配置文件来存储应用程序的配置信息。这些配置文件通常称为App.config或Web.config文件,它们用于存储应用程序的连接字符串、数据库路径、日志记录设置等。

以下是使用C#读取和写入配置文件的示例代码:

读取XML配置文件:

using System.Configuration;  
  
// 读取AppSettings节中的值  
string settingValue = ConfigurationManager.AppSettings["settingKey"];  
  
// 读取connectionString节中的值  
string connectionString = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;

写入XML配置文件:

using System.Configuration;  
  
// 获取AppSettings节  
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);  
ConfigurationSection appSettings = config.GetSection("appSettings");  
  
// 添加或修改AppSettings的值  
appSettings["settingKey"] = "newValue";  
  
// 保存配置文件  
config.Save(ConfigurationSaveMode.Modified);  
ConfigurationManager.RefreshSection("appSettings");

读取JSON配置文件:

using System.IO;  
using Newtonsoft.Json;  
  
// 读取JSON配置文件中的值  
string json = File.ReadAllText("path/to/config/file.json");  
dynamic config = JsonConvert.DeserializeObject(json);  
string settingValue = config.settingKey; // 假设配置文件中的键为"settingKey"

写入JSON配置文件:

using System.IO;  
using Newtonsoft.Json;  
  
// 创建要写入JSON配置文件的对象  
dynamic configObject = new ExpandoObject();  
configObject.settingKey = "newValue"; // 设置要写入的值  
  
// 将对象序列化为JSON字符串  
string json = JsonConvert.SerializeObject(configObject);  
  
// 将JSON字符串写入配置文件  
File.WriteAllText("path/to/config/file.json", json);