【问题标题】:Read INI in Visual Basic vb.NET在 Visual Basic vb.NET 中读取 INI
【发布时间】:2016-10-02 01:25:06
【问题描述】:

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

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

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

我使用的是 Visual Studio 2015,我曾尝试使用 Ludvik Jerabek 的 INI 阅读器 (http://www.codeproject.com/Articles/21896/INI-Reader-Writer-Class-for-C-VB-NET-and-VBScript),但没有成功!

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

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

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

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

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

然而这只是返回“0”

如果能找到一种方法从 INI 中获取此读数并将其转储到注册表,将不胜感激

【问题讨论】:

  • 这条线是不是可能期望一个序数位置来代替字符串? ini.Sections("Service").Keys("Service Name") 例如ini.Sections(1)。等
  • Dim readValue As String = ini.Sections("Service").Keys("Service Name") 和您的 GetPrivateProfileString function 作为字符串而不是整数。您可以稍后从字符串转换为整数。
  • 将它们设置为字符串类型不起作用,仍然是同样的错误/问题

标签: vb.net ini


【解决方案1】:

使用给定的 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

【讨论】:

    【解决方案2】:

    作为替代方案,原始方法的代码非常接近正确,但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
    

    如果您不想使用 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
    

    【讨论】:

      【解决方案3】:

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

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

      公开声明函数 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)

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

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

      公共共享函数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)
      

      结束函数

      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)
      

      结束子


      这在 VB 2010 中仍然有效

      【讨论】:

        猜你喜欢
        • 2017-10-20
        • 1970-01-01
        • 2015-10-02
        • 2014-06-09
        • 2013-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-24
        相关资源
        最近更新 更多