从INI文件中读取

Dar*_*cek 4 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
Run Code Online (Sandbox Code Playgroud)

如果我有一个名为'c:\ temp\test.ini'的INI文件,请使用以下数据:

[testApp]
KeyName=keyValue
KeyName2=keyValue2
Run Code Online (Sandbox Code Playgroud)

如何检索KeyName和KeyName2的值?

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

    Dim strData As String
    GetPrivateProfileString("testApp", "KeyName", "Nothing", strData, Len(strData), "c:\temp\test.ini")
    MsgBox(strData)
Run Code Online (Sandbox Code Playgroud)

Mar*_*all 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
Run Code Online (Sandbox Code Playgroud)