C# 读写 ini

很久没写了
最近需要用到ini文件的读写
没接触过来尝试一下
参考文章:
https://dotblogs.com.tw/atowngit/2009/09/01/10358

在这里插入图片描述在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,你可以使用 `System.IO` 命名空间中的 `StreamReader` 和 `StreamWriter` 类来实现批量读写INI文件。以下是一个简单的示例代码: ```csharp using System.IO; // 批量读取INI文件 public static Dictionary<string, string> ReadIniFile(string filePath) { Dictionary<string, string> iniData = new Dictionary<string, string>(); using (StreamReader reader = new StreamReader(filePath)) { string line; string currentSection = ""; while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (line.StartsWith("[") && line.EndsWith("]")) { currentSection = line.Substring(1, line.Length - 2); } else if (!string.IsNullOrWhiteSpace(line) && !line.StartsWith(";")) { int separatorIndex = line.IndexOf('='); if (separatorIndex > 0) { string key = line.Substring(0, separatorIndex).Trim(); string value = line.Substring(separatorIndex + 1).Trim(); if (!string.IsNullOrEmpty(currentSection)) { key = currentSection + ":" + key; } iniData[key] = value; } } } } return iniData; } // 批量写入INI文件 public static void WriteIniFile(string filePath, Dictionary<string, string> iniData) { using (StreamWriter writer = new StreamWriter(filePath)) { foreach (var item in iniData) { string[] sectionsAndKey = item.Key.Split(':'); string section = sectionsAndKey.Length > 1 ? sectionsAndKey[0] : ""; string key = sectionsAndKey.Length > 1 ? sectionsAndKey[1] : sectionsAndKey[0]; string value = item.Value; if (!string.IsNullOrEmpty(section)) { writer.WriteLine($"[{section}]"); } writer.WriteLine($"{key}={value}"); } } } ``` 使用示例: ```csharp // 批量读取INI文件 string filePath = "path/to/your/inifile.ini"; Dictionary<string, string> iniData = ReadIniFile(filePath); // 修改或添加INI配置项 iniData["Section1:Key1"] = "Value1"; iniData["Section2:Key2"] = "Value2"; // 批量写入INI文件 WriteIniFile(filePath, iniData); ``` 请确保你已包含 `System.IO` 命名空间,并将 `path/to/your/inifile.ini` 替换为你的实际INI文件路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值