如何从 ini 文件中获取所有部分名称

How to get All Section Names from ini file

我想从 ini 中获取部分列表 file.I 现在我的文件中只有一个部分,我的以下代码返回 null。

我尝试了各种使用 GetSectionNamesListA 和 GetPrivateProfileSectionNames 的方法。 None 其中似乎有帮助

   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('[=10=]');
        return sectionNames;
    }

使用:

[DllImport("kernel32")]
  static extern int GetPrivateProfileSectionNames(byte[] pszReturnBuffer, int nSize, string lpFileName);

尽管存在一个部分,但我返回的是空值。

最简单的方法可能是使用像 INI Parser

这样的库

下面是一个使用库的例子:

var parser = new FileIniDataParser();
IniData data = parser.ReadFile("file.ini");
foreach (var section in data.Sections)
{
   Console.WriteLine(section.SectionName);
}

并且在您的情况下 GetPrivateProfileSectionNames 没有给出部分名称,因为它需要文件的完整路径。如果你给它一个相对路径,它会尝试在 Windows 文件夹中找到它。

The name of the initialization file. If this parameter is NULL, the function searches the Win.ini file. If this parameter does not contain a full path to the file, the system searches for the file in the Windows directory.

解决这个问题的一种方法是使用 Path.GetFullPath(path):

path = Path.GetFullPath(path);

而这个page显示了GetPrivateProfileSectionNames的正确用法:

[DllImport("kernel32")]
static extern uint GetPrivateProfileSectionNames(IntPtr pszReturnBuffer, uint nSize, string lpFileName);

public static string[] SectionNames(string path)
{
    path = Path.GetFullPath(path);
    uint MAX_BUFFER = 32767;
    IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER);
    uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
    if (bytesReturned == 0)
        return null;
    string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
    Marshal.FreeCoTaskMem(pReturnedString);
    //use of Substring below removes terminating null for split
    return local.Substring(0, local.Length - 1).Split('[=12=]');
}