2012-06-28 165 views
4

我發現寫入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 

如果我有一個名爲INI文件 'C:\ TEMP \ test.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) 
+0

你得到什麼錯誤? –

+0

沒有錯誤,只是一個空字符串。 strData返回時沒有數據。 –

回答

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 
+0

太棒了。謝謝馬克。完善。 –

+0

@Darryl歡迎您 –