Problem: Reading ini-File

Hi,
I've a problem reading an ini-File. I use the Function 'GetPrivateProfileStringA() which seems to work perfectly. The problems started when I declared my variables like this:

Dim s As String = ""
Dim n As Integer
n = GetPrivateProfileStringA(Section, Key, "doesntexist", s, 255, IniPath())

The variable 's' that should contain the string was empty. After hours of fighting against the code, I tried something like this:

Dim s As String = " "
Dim n As Integer
n = GetPrivateProfileStringA(Section, Key, "doesntexist", s, 255, IniPath())

Now, it worked great. There was my result in the variable. But now I recognized a further problem: The function doesn't overwrite all 100 spaces of 's'. Instead of this, it overwrites space for space. If the received string is 'test', the variable s contains the sting 'test' and 96 further spaces. I can't eliminate the spaces by Trim() or another function like this...

Do you have a solution for this

Thanks very much...


Answer this question

Problem: Reading ini-File

  • Karen Chen

    GetPrivateProfileString returns the number of characters it put in the string. You can use that info:

    Dim s As String = Space(256)
    Dim n As Integer = GetPrivateProfileStringA(Section, Key, "doesntexist", s, s.Length-1, IniPath())
    s = Left(s, n)

    You really should use a StringBuilder instead of a String but you'll probably get away with it.



  • Christopher

    Hi,

    Thanks for your replies. I had to modifiy your code example like this:

    Dim s As String = Space(256)
    Dim n As Integer = GetPrivateProfileStringA(Section, Key, "doesntexist", s, s.Length - 1, IniPath())
    s = Left(s, n + 1)

    Because the one without "+1" cut one char of the string. Now it works perfectly!

  • northern

    The 'returned' value is actually null terminated (not sure if it fills the whole thing with nulls). You may be able to find the first null (ascii character 0), and trim off the remaining length.

    Or you culd try Trim(chr(0)) that may work, off the top of my head.



  • Problem: Reading ini-File