在 Visual Basic vb.NET 中读取 INI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37589627/
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-17 19:54:41  来源:igfitidea点击:

Read INI in Visual Basic vb.NET

vb.netini

提问by Gaza

I'm trying to read a INI file then dump the values into the registry for a setup application to function.

我正在尝试读取 INI 文件,然后将值转储到注册表中,以便安装应用程序运行。

The INI file looks like this

INI 文件看起来像这样

[Setup Components]

Sybase Adaptive Server Anywhere Client=Yes

Borland Database Engine=Yes

BDERoot=c:\Program Files\Borland\BDE 

Program Shortcuts=Yes

ODBC Data Service Name=Yes

Local Client = Yes

Sybase Admin = Yes

Sybase Directory= C:\Program Files\SQL Anywhere 16

DBRoot=c:\Database

Word Link=Yes

Installation Root Folder=c:\program

FireDAC=DB=asa16;eng=ENGINE;dbn=DBNAME;links=TCPIP{Host=127.0.0.1;Port=2638}

[Program Shortcuts]

Desktop=Yes
Start Menu=Yes

Program Title=PROGRAM

EXE Pathname=c:\program.exe

Parameters=DBNAME

Starting Directory=c:\

Icon=icon.ICO


[ODBC Data Service Name]

Data Service Name=DBNAME

Database File Name=c:\database\database.db

Database Name=DBNAME

Server Name=ENGINE

Comm Links=TCPIP{}

PrefetchBuffer=6000

PrefetchRows=50

CommBufferSize=1460

Compress=no


[Service]

Service Name=SQLANYs_DBNAME
Display Name=SQL Anywhere - DBNAME
Service Group=SQLANYServer
Params=-n DBNAME -x TCPIP{} "C:\database\database.db" -n DBNAME

So I need all those items to be dumped into the registry easily.

所以我需要将所有这些项目轻松转储到注册表中。

I'm using Visual Studio 2015, I did attempt to use Ludvik Jerabek's INI reader (http://www.codeproject.com/Articles/21896/INI-Reader-Writer-Class-for-C-VB-NET-and-VBScript) but had no luck getting that to function!

我正在使用 Visual Studio 2015,我确实尝试使用 Ludvik Jerabek 的 INI 阅读器(http://www.codeproject.com/Articles/21896/INI-Reader-Writer-Class-for-C-VB-NET-and- VBScript)但没有运气让它起作用!

The code i did use for the above was the following:

我在上面使用的代码如下:

Dim ini = New IniFile()
ini.Load("setup.ini")
Dim readValue = ini.Sections("Service").Keys("Service Name")
MessageBox.Show(readValue.ToString)

When running this code i got the following error : "Conversion from string "Service" to type "Integer" is not valid. -Also this method means naming each and every key in the INI file which would be quite some task!

运行此代码时,我收到以下错误:“从字符串“服务”转换为“整数”类型无效。-此外,此方法意味着命名 INI 文件中的每个键,这将是一项艰巨的任务!

I then went down another method after reading some help questions on here and i used the following:

在阅读了一些帮助问题后,我采用了另一种方法,并使用了以下方法:

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


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim sb As StringBuilder
    sb = New StringBuilder(500)
    Dim readVal = GetPrivateProfileString("Service", "Service Name", "", sb, sb.Capacity, "setup.ini")
    MessageBox.Show(readVal.ToString)
End Sub

However this just returns "0"

然而这只是返回“0”

Any help would be grateful to find a way to get this reading from the INI and dumping to the registry

任何帮助将不胜感激找到一种方法从 INI 读取此读数并转储到注册表

回答by Andrew Mortimer

Using the given IniFile class, this will get you to the config setting values:

使用给定的 IniFile 类,这将使您获得配置设置值:

Private Sub INIButtonTest_Click(sender As Object, e As EventArgs) Handles INIButtonTest.Click
    Try

        Dim iniFilePath As String = "H:\Dev\StackOverflow\StackOverflowTest\StackOverflowApp\bin\Debug\test.ini"

        Dim myIniFile As New IniFile
        myIniFile.Load(iniFilePath)

        Dim myValue As String = getIniValue(myIniFile, "Service", "Service Name")

        If Not String.IsNullOrEmpty(myValue) Then
            MessageBox.Show(String.Format("Found value: [{0}]", myValue))
        End If

    Catch ex As Exception
        MessageBox.Show(String.Concat("Something went wrong:", ex.Message))
    End Try
End Sub

Private Function getIniValue(iniFileInstance As IniFile, sectionName As String, sectionKey As String) As String

    Dim myValue As String = String.Empty

    For Each sect As IniFile.IniSection In iniFileInstance.Sections
        If sect.Name = sectionName Then
            For Each key As IniFile.IniSection.IniKey In sect.Keys
                If key.Name = sectionKey Then
                    myValue = key.GetValue
                    Exit For
                End If
            Next
            Exit For
        End If
    Next

    Return myValue

End Function

回答by theB

As an alternate, the code for the original approach is veryclose to correct, but GetPrivateProfileStringdoesn't actually exist in Kernel32.dll. You need to add a W to the name, which makes the corrected code:

作为替代,原始方法的代码非常接近正确,但GetPrivateProfileString实际上并不存在于 Kernel32.dll 中。您需要在名称中添加一个 W,从而使代码更正:

' With these imports
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Imports System.Text

' Note the W on the function name
Private Declare Auto Function GetPrivateProfileStringW 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


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim sb As New StringBuilder(500)
    Dim result As Integer = GetPrivateProfileStringW("Service", "Service Name", "", sb, sb.Capacity, "setup.ini")
    If result > 0 Then
        MessageBox.Show(sb.ToString())
    Else
        Dim ex As New Win32Exception(Marshal.GetLastWin32Error())
        MessageBox.Show(ex.Message)
    End If
End Sub

If you prefer not to use the W, or you want to call your function something different, you can also use the DllImportAttributeand change the function declaration to:

如果您不想使用 W,或者您想调用不同的函数,您还可以使用DllImportAttribute并将函数声明更改为:

<DllImport("Kernel32.dll", CharSet:=CharSet.Auto, 
           SetLastError:=True, EntryPoint:="GetPrivateProfileStringW")>
Private Shared Function GetPrivateProfileString(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
End Function

回答by Kevin

This is what I have used since VB 3.0 and it has worked with all versions of windows since 3.1. There have been a few modifications to make it fit into the conventions of the newer dev tools but essentially they are the same routines.

这是我自 VB 3.0 以来一直使用的,并且自 3.1 以来它已与所有版本的 Windows 一起使用。进行了一些修改以使其适合较新的开发工具的约定,但本质上它们是相同的例程。

These must be in a public class or in the public area of a form:

这些必须在公共类或公共区域中:

Public Declare Function OSGetPrivateProfileString% Lib "kernel32" Alias "GetPrivateProfileStringA"(ByVal AppName As String, ByVal KeyName As String, ByVal keydefault As String, ByVal ReturnString As String, ByVal NumBytes As Integer, ByVal FileName As String)

Public Declare Function OSGetPrivateProfileString% Lib "kernel32" Alias "GetPrivateProfileStringA"(ByVal AppName As String, ByVal KeyName As String, ByVal keydefault As String, ByVal ReturnString As String, ByVal NumBytes As Integer, ByVal FileName As String)

Public Declare Function OSWritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA"(ByVal AppName As String, ByVal KeyName As String, ByVal keydefault As String, ByVal FileName As String) As Integer

公共声明函数 OSWritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA"(ByVal AppName As String, ByVal KeyName As String, ByVal keydefault As String, ByVal FileName As String) As Integer

Then, somewhere in your form's code area or if you have a "functions.vb" class (where the above would be declared) place these two:

然后,在表单代码区域的某个地方,或者如果您有一个“functions.vb”类(上面将在其中声明)放置这两个:

Public Shared Function GetINIString(ByVal strItem As String, ByVal strDefault As String, ByVal strSection As String, ByVal filename As String) As String

公共共享函数 GetINIString(ByVal strItem As String, ByVal strDefault As String, ByVal strSection As String, ByVal filename As String) As String

    Const BUFFERSIZE As Integer = 16768

    Dim strTemp As New String(Chr(0), BUFFERSIZE)
    Dim stringSize As Long = 0

    stringSize = OSGetPrivateProfileString%(strSection, strItem, strDefault, strTemp, BUFFERSIZE, filename)

    Return Strings.Left(strTemp, stringSize)

End Function

结束函数

AND

Public Shared Sub PutINIString(strItem As String, strValue As String, strSection As String, iniFilename As String)

Public Shared Sub PutINIString(strItem As String, strValue As String, strSection As String, iniFilename As String)

Dim i As Integer = 0

i = OSWritePrivateProfileString(strSection, strItem, strValue, iniFilename)

End Sub

结束子



This continues to work in VB 2010

这在 VB 2010 中继续有效