如何为Danny Beckett的INI文件类添加读取整节至字典的功能?
给INI类添加读取整节的方法
针对你正在使用的INI操作类,你可以通过以下两种方式实现ReadSection方法,满足读取指定节下所有键值对的需求:
方法一:基于Windows API实现(适配原类逻辑)
利用Win32 API直接枚举指定节下的所有键,再逐个读取对应值,和原类的实现逻辑保持一致:
public Dictionary<string, string> ReadSection(string section) { var keyValuePairs = new Dictionary<string, string>(); const int bufferSize = 1024 * 10; // 10KB缓冲区,可按需调整 char[] buffer = new char[bufferSize]; // 获取指定节下所有键,键之间用null字符分隔 int bytesReturned = GetPrivateProfileString(section, null, null, buffer, bufferSize, _path); if (bytesReturned > 0) { int currentIndex = 0; // 遍历缓冲区提取每个键 while (currentIndex < bytesReturned) { int nullIndex = Array.IndexOf(buffer, '\0', currentIndex); string key = new string(buffer, currentIndex, nullIndex - currentIndex); currentIndex += key.Length + 1; // 调用原类的Read方法获取对应值 string value = Read(section, key); keyValuePairs.Add(key, value); } } return keyValuePairs; }
注意:确保你的INI类中已包含GetPrivateProfileString的P/Invoke签名(原类通常已自带):
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, char[] lpReturnedString, int nSize, string lpFileName);
方法二:直接解析INI文件(跨平台友好)
如果需要脱离Windows API依赖,可直接读取文件内容进行解析,适合跨平台场景:
public Dictionary<string, string> ReadSection(string section) { var keyValuePairs = new Dictionary<string, string>(); bool isTargetSection = false; foreach (string line in File.ReadAllLines(_path)) { string trimmedLine = line.Trim(); // 跳过空行和注释行 if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith(";")) continue; // 判断是否进入目标节 if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]")) { string currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2); isTargetSection = currentSection.Equals(section, StringComparison.OrdinalIgnoreCase); continue; } // 在目标节内解析键值对 if (isTargetSection) { int equalsIndex = trimmedLine.IndexOf('='); if (equalsIndex > 0) { string key = trimmedLine.Substring(0, equalsIndex).Trim(); string value = trimmedLine.Substring(equalsIndex + 1).Trim(); keyValuePairs[key] = value; } } } return keyValuePairs; }
使用示例
调用方法获取供应商更新时间字典:
var ini = new IniFile("your-config.ini"); Dictionary<string, string> supplierLastUpdate = ini.ReadSection("SupplierLastUpdate"); // 遍历输出结果 foreach (var kvp in supplierLastUpdate) { Console.WriteLine($"供应商:{kvp.Key},最后更新时间:{kvp.Value}"); }
内容的提问来源于stack exchange,提问作者Griffin
相关产品推荐
相关产品推荐

