新建项目,名称请用带中文的名称(如 哦哦 vbtest)
Class1.vb
Imports System.Text
Public Class Ini
Private _path As String '配置文件的路径
Public Sub New(ByVal path As String)
_path = path
End Sub
'定义API
'操作INI文件的API
Private 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 Int32, ByVal lpFileName As String) As Int32
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" _
(ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Int32
'定义函数
'操作INI文件
''' <summary>
''' 添加设置
''' </summary>
''' <param name="section">块</param>
''' <param name="key">节点</param>
''' <param name="kvalue">值</param>
''' <returns>返回kvalue的值(即节点值)</returns>
''' <remarks></remarks>
Public Function AddSetting(ByVal section As String, ByVal key As String, ByVal kvalue As String) As String
On Error Resume Next
WritePrivateProfileString(section, key, kvalue, _path)
Return kvalue
End Function
''' <summary>
''' 获取设置
''' </summary>
''' <param name="section">块</param>
''' <param name="key">节点</param>
''' <returns>返回节点值</returns>
''' <remarks></remarks>
Public Function GetSetting(ByVal section As String, ByVal key As String) As String
Dim strIni As New StringBuilder(32768)
Dim num As Int32 = GetPrivateProfileString(section, key, "", strIni, 32768, _path)'这里的_path有问题
Return strIni.ToString
End Function
End Class
form1.vb(窗体上就一个按钮 button1)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dim p as string=IO.Path.Combine(Application.StartupPath, "version.ini")
Dim cls As New Ini(p)'设置断点假设p="哦哦 vbtest\哦哦 vbtest\bin\Debug\version.ini"
Dim NewVersion As String = cls.GetSetting("version", "version")
MsgBox(NewVersion)
Dim OldVersion As String = cls.GetSetting("WhatsNew", "version")
MsgBox(OldVersion)
End Sub
version.ini
[version]
version=1.0.0.0
[WhatsNew]
version=1.0.0.01
调试程序,到断点处,开始单步执行
第一次运行到出问题的地方时,_path="哦哦 vbtest\哦哦 vbtest\bin\Debug\version.ini"
第二次运行到出问题的地方时,_path="哦哦 vbtest\哦哦 vbtest\bin\Debug\version.i"(可能有所不同,但是和第一次的就是不同),第三次运行到此处时,值和第二次的相同
意思就是,同一个类的实例,多次运行后,类内部的值会发生变化?