lipkau / PsIni

Work with INI files in PowerShell using hashtables
http://lipkau.github.io/PsIni
MIT License
151 stars 50 forks source link

Files edited with PsIni can't be read with GetPrivateProfileString #55

Closed jpann closed 4 years ago

jpann commented 4 years ago

I'm having trouble getting any file edited with PsIni to have any value read using GetPrivateProfileString. GetPrivateProfileString always return the default value in the call. After this happens, even if I manually edit the ini file in something like notepad or ultraedit to revert back to the previous value, the calls to GetPrivateProfileString still can't read this value.

Create file at 'C:\Test.ini' and put in contents:

[Startup]
key=value

Update ini file:

$ini = Get-IniContent "C:\Test.ini"
$ini["Startup"]["key"] = "value_changed"
$ini | Out-IniFile -FilePath "C:\Test.ini" -Force

Demo script in linqpad:

[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

void Main()
{
    string path = @"C:\Test.ini";

    string value = ReadString(path, "Startup", "key", "");
    Console.WriteLine(value); // this is always ""
}

public string ReadString(string file, string section, string key, string defValue)
{
    StringBuilder stringBuilder = new StringBuilder(1024);
    GetPrivateProfileString(section, key, defValue, stringBuilder, 1024, file);
    return stringBuilder.ToString();
}
jpann commented 4 years ago

Looks like using -Encoding ascii paired with Out-IniFile resolved it. I guess GetPrivateProfileStringdoes not like UTF8 encoded INI files. Today I learned :)