【发布时间】:2019-10-04 15:54:00
【问题描述】:
我想从 ini 文件中获取节列表。我的文件中现在只有一个节,我的下面的代码返回 null。
我尝试了使用 GetSectionNamesListA 和 GetPrivateProfileSectionNames 的各种方法。他们似乎都没有帮助
public string[] GetSectionNames(string path)
{
byte[] buffer = new byte[1024];
GetPrivateProfileSectionNames(buffer, buffer.Length, path);
string allSections = System.Text.Encoding.Default.GetString(buffer);
string[] sectionNames = allSections.Split('\0');
return sectionNames;
}
使用:
[DllImport("kernel32")]
static extern int GetPrivateProfileSectionNames(byte[] pszReturnBuffer, int nSize, string lpFileName);
尽管存在一个部分,但我返回 null。
【问题讨论】:
-
人们还在使用ini文件?!
-
大声笑@DavidG - 正是我的想法。但说真的,使用
File.ReadAllLines()将 ini 文件作为列表读取是迄今为止获取所有部分的最简单方法。您只需要找到\[.*\](或简单的text.StartsWith("[") && text.Trim().EndsWith("]"))正则表达式的所有组匹配 -
我在 @Archer..ini 文件很容易解析。我什至不会使用 Windows API。此外,如果有多个与您的代码没有相同名称的部分,Windows API 将会出错。