Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetPrivateProfileString() returns empty string, despite having a default

Private Declare Function GetPrivateProfileString Lib "kernel32" Alias _
        "GetPrivateProfileStringA" (ByVal lpApplicationName As String, _
            ByVal lpKeyName As String, _
            ByVal lpDefault As String, _
            ByVal lpReturnedString As String, _
            ByVal nSize As Integer, ByVal lpFileName As String) As Integer
Dim value As String = ""
Dim length As Integer
Dim IniFileName As String

GetPrivateProfileString("Config", "UserName", "None", value, length, IniFileName)

but value contains an empty string!?

I confes to being a VB n00b, less than a week, in fact, but I can't see what's wrong there. The file exists, it contains a section called "Config" which has an entry called "UserName" with a value - but even if not, wouldn't value take the default?

(And, no, I don't want to use the registry, thanks ;-)


Edit: It's not returning an empty string - it's returning whatever I initialize value to before calling GetPrivateProfileString().

Which is to say that if I

Dim value As String = "xxx"

then it stil contains "xxx" after the call and not the default value.

like image 276
Mawg says reinstate Monica Avatar asked Aug 11 '26 08:08

Mawg says reinstate Monica


2 Answers

Make sure codepage of your INI-file is ANSI. I was getting empty results because my ini was in UTF-8.

Was not obvious for me.

like image 74
hypers Avatar answered Aug 14 '26 10:08

hypers


You have to set the size in the params, and reserve space for the result. Insert this lines before the call to the function:

value = space(255)
length = len(value)

Forgot something: you have to use the return value of the function, as this is the length of the actual value you get, and use a Left(value,length) to get your real answer.

like image 28
dwo Avatar answered Aug 14 '26 12:08

dwo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!