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?
YES, You CAN use a StringBuilder if you like and here is the solution:
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath);
public string PopValue(string section, string key)
{
StringBuilder sb = new StringBuilder(4096);
int n = GetPrivateProfileString(section, key, "", sb, 4096, path);
if(n<1) return string.Empty;
return sb.ToString();
}
The problem is that you passed in a zero length when you passed sb.Length and it was interpreted by the imported function that there was NO SPACE in which to write the return value - so it wrote nothing.