I'm trying to convert a working VB.NET WinForms application to C#, and I'm
having trouble with the string buffer being returned from a Win32 API call.

First, my working VB.NET code:
    Public 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

    lngSize = 127
    strDBLocation = Space(lngSize) & Chr(0)
    lngDummy = GetPrivateProfileString("DBLocation", "Path", _
            vbNullString, strDBLocation, lngSize, strINIPath)
    strDBLocation = Left(strDBLocation, InStr(strDBLocation, Chr(0)) - 1)

This code returns the correct strDBLocation string.  It also sets lngDummy
to the length of the returned string (23).

Now, what I think is the equivalent C# code:
    [DllImport("kernel32.dll", EntryPoint="GetPrivateProfileStringA",
 CharSet=CharSet.Ansi)]
 public static extern int GetPrivateProfileString(
 string lpApplicationName, string lpKeyName, string lpDefault,
 string lpReturnedString, int nSize, string lpFileName);

    intSize = 127;
    strDBLocation = new string(' ', intSize) + (char) 0;
    intDummy = GetPrivateProfileString("DBLocation", "Path", null,
 strDBLocation, intSize, strINIPath);
    i = strDBLocation.IndexOf((char) 0);
    if (i >= 0)
 strDBLocation = strDBLocation.Substring(0, i);

When I run this in the identical environment, intDummy gets set to 23
(which is correct), but strDBLocation remains the same as before the call
to GetPrivateProfileString (a 127-char string filled with spaces).  I
verified that strINIPath is set to the same value as in the VB app.

Can someone please tell me what I'm doing wrong?  (I've tried switching to
CharSet.Auto and CharSet.Unicode, with no success.)

Bill

You can read messages from the DOTNET archive, unsubscribe from DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to