读取长度超255字符的INI键值报错,求解决方案
解决C#读取INI超长键值报错的问题
你当前使用的IniFile类应该是基于Windows原生的GetPrivateProfileStringAPI实现的,这个API默认缓冲区长度限制为255字符,当键值内容超过该长度时就会读取失败或截断,进而导致后续处理报错。
以下是具体解决方案:
1. 替换为支持超长键值的自定义IniFile类
自己实现不依赖系统API的INI解析逻辑,直接读取文件内容并解析,突破字符长度限制:
using System; using System.Collections.Generic; using System.IO; using System.Linq; public class CustomIniFile { private readonly Dictionary<string, Dictionary<string, string>> _sections = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); public CustomIniFile(string filePath) { Load(filePath); } private void Load(string filePath) { if (!File.Exists(filePath)) return; string currentSection = null; foreach (var line in File.ReadAllLines(filePath).Select(l => l.Trim())) { // 跳过空行和注释 if (string.IsNullOrEmpty(line) || line.StartsWith(";") || line.StartsWith("#")) continue; // 解析节头 [SectionName] if (line.StartsWith("[") && line.EndsWith("]")) { currentSection = line.Substring(1, line.Length - 2).Trim(); if (!_sections.ContainsKey(currentSection)) _sections[currentSection] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); continue; } // 解析键值对 Key=Value if (currentSection != null) { var splitIndex = line.IndexOf('='); if (splitIndex > 0) { var key = line.Substring(0, splitIndex).Trim(); var value = line.Substring(splitIndex + 1).Trim(); _sections[currentSection][key] = value; } } } } public string Read(string key, string section) { if (_sections.TryGetValue(section, out var sectionDict) && sectionDict.TryGetValue(key, out var value)) return value; return string.Empty; } }
2. 优化ListBox加载代码(简化逻辑)
替换原有goto写法,用更清晰的遍历逻辑处理分割后的内容:
// 使用自定义类读取INI内容 string t1Stone = new CustomIniFile(iniFilePath).Read("name", "Islands"); Console.WriteLine(t1Stone); if (!string.IsNullOrEmpty(t1Stone)) { // 分割时自动移除空元素 string[] t1StoneValues = t1Stone.Split(',', StringSplitOptions.RemoveEmptyEntries); foreach (var item in t1StoneValues) { // 遇到"end"就停止添加 if (item.Equals("end", StringComparison.OrdinalIgnoreCase)) break; listBoxWyspy.Items.Add(item); } }
补充说明
- 自定义
CustomIniFile类直接读取完整文件内容逐行解析,没有系统API的字符长度限制,可处理任意长度的键值内容。 - 优化后的加载代码通过
foreach遍历数组,自动处理索引,同时用StringSplitOptions.RemoveEmptyEntries过滤空元素,无需单独判断空字符串。
内容的提问来源于stack exchange,提问作者Michal O
相关产品推荐
相关产品推荐

