vb.net 从 INI 文件中读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11238898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:10:51  来源:igfitidea点击:

Reading from an INI file

vb.netini

提问by Darryl Janecek

I find it very easy to write to a INI file, but am having some trouble in retrieving the data from an already created INI file.

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

I am using this function:

我正在使用这个功能:

    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

If I have an INI file called 'c:\temp\test.ini', with the following data:

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

[testApp]
KeyName=keyValue
KeyName2=keyValue2

How can I retrieve the values of KeyName and KeyName2?

如何检索 KeyName 和 KeyName2 的值?

I have tried this code, with no success:

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

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

回答by Mark Hall

Going to the Pinvoke.NetWeb site and modifying their example worked, their Function declaration is different.

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

Modified Example

修改示例

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