4

我发现写入 INI 文件非常容易,但在从已创建的 INI 文件中检索数据时遇到了一些麻烦。

我正在使用这个功能:

    Public Declare Unicode Function GetPrivateProfileString Lib "kernel32" _
    Alias "GetPrivateProfileStringW" (ByVal lpApplicationName As String, _
    ByVal lpKeyName As String, ByVal lpDefault As String, _
    ByVal lpReturnedString As String, ByVal nSize As Int32, _
    ByVal lpFileName As String) As Int32

如果我有一个名为“c:\temp\test.ini”的 INI 文件,其中包含以下数据:

[testApp]
KeyName=keyValue
KeyName2=keyValue2

如何检索 KeyName 和 KeyName2 的值?

我试过这段代码,但没有成功:

    Dim strData As String
    GetPrivateProfileString("testApp", "KeyName", "Nothing", strData, Len(strData), "c:\temp\test.ini")
    MsgBox(strData)
4

1 回答 1

6

转到Pinvoke.Net网站并修改他们的示例工作,他们的函数声明是不同的。

修改示例

Imports System.Runtime.InteropServices
Imports System.Text
Module Module1
    Private Declare Auto Function GetPrivateProfileString Lib "kernel32" (ByVal lpAppName As String, _
            ByVal lpKeyName As String, _
            ByVal lpDefault As String, _
            ByVal lpReturnedString As StringBuilder, _
            ByVal nSize As Integer, _
            ByVal lpFileName As String) As Integer

    Sub Main()

        Dim res As Integer
        Dim sb As StringBuilder

        sb = New StringBuilder(500)
        res = GetPrivateProfileString("testApp", "KeyName", "", sb, sb.Capacity, "c:\temp\test.ini")
        Console.WriteLine("GetPrivateProfileStrng returned : " & res.ToString())
        Console.WriteLine("KeyName is : " & sb.ToString())
        Console.ReadLine();

    End Sub
End Module
于 2012-06-28T06:40:04.503 回答