雖然 VB.NET 讀取 XML 設定文件很方便,但某些時候 INI 設定檔反而方便。然而 VB.NET 要讀取 INI 卻不如 VB5/6(API) 那樣方便,於是參考了別人的做法再加以強化,便產生 GetIniInfo 此一 Function。說穿了,就是用 StreamReader 這物件讀取各行並解析,很簡單的。
'參數說明:strIniFile(INI文件),strSection(INI文件中設置的部分名稱)
Imports System.IO
Function GetIniInfo(ByVal strIniFile As String, ByVal strSection As String) As String
If Not File.Exists(strIniFile) Then
Return "檔案 " & strFile & " 不存在,請確認路徑或檔案名稱是否正確。"
Exit Function
End If
Dim objINIRead As New StreamReader(strIniFile)
Dim strTheINI As String = objINIRead.ReadToEnd
Dim i As Integer
Dim intLine As Integer
Dim blnNoSection As Boolean = False
Dim strGetValue As String = ""
Dim strLineStream as Variant
strLineStream = strTheINI.Split(Chr(13))
intLine = UBound(strLineStream)
For i = 0 To intLine
If strLineStream(i).indexof("=") > 0 Then
If strLineStream(i).split("=")(0).trim() = strSection Then
blnNoSection = True
strGetValue = strLineStream(i).split("=")(1).trim()
Exit For
End If
End If
Next i
If blnNoSection = True Then
Return strGetValue
Else
Return "無指定 " & strSection & " 之值。"
End If
End Function
ex:
sample.ini 內容:
[Info]
code=vista711
number=300
MsgBox(GetIniInfo(Application.StartupPath & "\set.ini", "name"))
0 留言