2012年10月29日 星期一

如何讀取與寫入 ini 檔用 VB.NET

Imports System.Text


Imports System.Runtime.InteropServices



Public Class Form1



'2.宣告方法:

Public Declare Function GetPrivateProfileString Lib "kernel32" _

Alias "GetPrivateProfileStringA" ( _

ByVal lpApplicationName As String, _

ByVal lpKeyName As String, _

ByVal lpDefault As String, _

ByVal lpReturnedString As StringBuilder, _

ByVal nSize As UInt32, _

ByVal lpFileName As String) As UInt32

Public Declare Function WritePrivateProfileString Lib "kernel32" _

Alias "WritePrivateProfileStringA" ( _

ByVal lpApplicationName As String, _

ByVal lpKeyName As String, _

ByVal lpReturnedString As StringBuilder, _

ByVal lpFileName As String) As UInt32





Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

'3.使用方式:

'讀出ini檔,區段裡的值:

Dim lReturnLen1 As UInt64

Dim lReturnLen2 As UInt64

Dim lReturnLen3 As UInt64



Dim sSection1 As String = "City" '區段

Dim sKey1 As String = "City_1" '區段中的值

Dim sKey2 As String = "City_2"

Dim sKey3 As String = "City_3"



Dim sSection2 As String = "food" '區段

Dim sKey4 As String = "food_1" '區段中的值

Dim sKey5 As String = "food_2"

Dim sKey6 As String = "food_3"



Dim sSection3 As String = "goods" '區段

Dim sKey7 As String = "goods_1" '區段中的值

Dim sKey8 As String = "goods_2"

Dim sKey9 As String = "goods_3"



Dim sKeyValue As New StringBuilder(1024)

Dim nSize As UInt32 = Convert.ToUInt32(1024)

Dim sinifilename As String = Application.StartupPath & "\\test.ini"

lReturnLen1 = GetPrivateProfileString(sSection1, sKey1, "", sKeyValue, nSize, sinifilename)

Label1.Text = sKeyValue.ToString



lReturnLen1 = GetPrivateProfileString(sSection1, sKey2, "", sKeyValue, nSize, sinifilename)

Label2.Text = sKeyValue.ToString

lReturnLen1 = GetPrivateProfileString(sSection1, sKey3, "", sKeyValue, nSize, sinifilename)

Label3.Text = sKeyValue.ToString



lReturnLen2 = GetPrivateProfileString(sSection2, sKey4, "", sKeyValue, nSize, sinifilename)

Label4.Text = sKeyValue.ToString

lReturnLen2 = GetPrivateProfileString(sSection2, sKey5, "", sKeyValue, nSize, sinifilename)

Label5.Text = sKeyValue.ToString

lReturnLen2 = GetPrivateProfileString(sSection2, sKey6, "", sKeyValue, nSize, sinifilename)

Label6.Text = sKeyValue.ToString



lReturnLen3 = GetPrivateProfileString(sSection3, sKey7, "", sKeyValue, nSize, sinifilename)

Label7.Text = sKeyValue.ToString

lReturnLen3 = GetPrivateProfileString(sSection3, sKey8, "", sKeyValue, nSize, sinifilename)

Label8.Text = sKeyValue.ToString

lReturnLen3 = GetPrivateProfileString(sSection3, sKey9, "", sKeyValue, nSize, sinifilename)

Label9.Text = sKeyValue.ToString



End Sub

End Class

沒有留言: