문제

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?

도움이 되었습니까?

해결책 2

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top