Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read all ini file values with GetPrivateProfileString

I need a way to read all sections/keys of ini file in a StringBuilder variable:

[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

...

private List<string> GetKeys(string iniFile, string category)
{
    StringBuilder returnString = new StringBuilder(255);            

    GetPrivateProfileString(category, null, null, returnString, 32768, iniFile);

    ...
}

In returnString is only the first key value! How it is possible to get all at once and write it to the StringBuilder and to List?

Thank you for your help!

greets leon22

like image 948
leon22 Avatar asked Aug 17 '11 08:08

leon22


2 Answers

Possible solution:

[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpszReturnBuffer, int nSize, string lpFileName);

private List<string> GetKeys(string iniFile, string category)
{

    byte[] buffer = new byte[2048];

    GetPrivateProfileSection(category, buffer, 2048, iniFile);
    String[] tmp = Encoding.ASCII.GetString(buffer).Trim('\0').Split('\0');

    List<string> result = new List<string>();

    foreach (String entry in tmp)
    {
        result.Add(entry.Substring(0, entry.IndexOf("=")));
    }

    return result;
}
like image 181
leon22 Avatar answered Oct 07 '22 18:10

leon22


I believe there's also GetPrivateProfileSection() that could help, but I agree with Zenwalker, there are libraries that could help with this. INI files aren't that hard to read: sections, key/value and comments is pretty much it.

like image 26
Neil Barnwell Avatar answered Oct 07 '22 18:10

Neil Barnwell