从INI文件中读取

时间:2012-06-28 06:06:19

标签: vb.net ini

我发现写入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)

1 个答案:

答案 0 :(得分: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