Search code examples
c#kernel32

GetPrivateProfileString not working .NET


I want to make an INI reader with GetPrivateProfileString. What I'm using:

public class Config
{
    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);

    private string path;

    public Config(string path)
    {
        this.path = path;
    }

    public string PopValue(string section, string key)
    {
        StringBuilder sb = new StringBuilder();
        GetPrivateProfileString(section, key, "", sb, sb.Length, path);
        return sb.ToString();
    }
}

Now my INI file:

[mysql]
host=localhost

And what I use:

Console.WriteLine(Configuration.PopValue("mysql", "host"));

However, it just prints out a blank line instead of localhost. What am I doing wrong?


Solution

  • If you can use third party library try using Nini. I use it and is very easy to create/manage complex INI files and is opensource.

    GetPrivateProfileString Signature is

    DWORD WINAPI GetPrivateProfileString(
      _In_   LPCTSTR lpAppName,
      _In_   LPCTSTR lpKeyName,
      _In_   LPCTSTR lpDefault,
      _Out_  LPTSTR lpReturnedString,
      _In_   DWORD nSize,
      _In_   LPCTSTR lpFileName
    );
    

    So out is not StringBuilder use String