|
对于类似格式如下的文件
[section]
key1=string1
key2=string2
.
.
.
windows提供了读取和写入键值的API函数GetPrivateProfileString和WritePrivateProfileString
以下提供了QTP中调用windows API函数尽情操作类似INI文件的类。直接拷贝到QTP中可以运行
'====================================
Extern.Declare micInteger, "GetPrivateProfileStringA", "Kernel32.dll", "GetPrivateProfileStringA", micString, micString, micString, micString+micByRef, micInteger, micString
Extern.Declare micInteger, "WritePrivateProfileStringA", "Kernel32.dll", "WritePrivateProfileStringA", micString, micString, micString, micString
Class INIClass
Private IniFileName
Public ErrorMsg
Private Sub Class_Initialize()
IniFileName = vbNullString
ErrorMsg = vbNullString
End Sub
Private Function IsINIFileExist()
If IniFileName = vbNullString Then
ErrorMsg = "No INI file exist"
IsINIFileExist = False
Exit Function
End If
IsINIFileExist = True
End Function
Public Sub SetINIPath(strFilePathName)
IniFileName = Trim(strFilePathName)
End Sub
Public Function WriteKey(Section, key, Value)
WriteKey = False
If Not IsINIFileExist() Then
Exit Function
End If
If CInt(Extern.WritePrivateProfileStringA(Section, key, Value, IniFileName)) = 0 Then
ErrorMsg = "Failed to write INI file"
Exit Function
End If
WriteKey = True
End Function
Public Function ReadKey(Section, key, Size)
Dim strKeyValue
ReadKey = vbNullString
If Not IsINIFileExist() Then
Exit Function
End If
strKeyValue = Space(Size)
If CInt(Extern.GetPrivateProfileStringA(Section, key, vbNullString, strKeyValue, Size, IniFileName)) > 0 Then
ReadKey = Trim(strKeyValue)
Else
ErrorMsg = "Can't find the value for key(" & key & ") in Section [" & Section & "]."
End If
End Function
End Class
'================================================
Set oINI = New INIClass
oINI.SetINIPath("C:\test.ini")
oINI.WriteKey "Section1", "key1", "value1"
oINI.WriteKey "Section1", "key2", "value2"
oINI.WriteKey "Section1", "key3", "value3"
oINI.WriteKey "Section2", "key1", "value4"
oINI.WriteKey "Section2", "key2", "value5"
oINI.WriteKey "Section2", "key3", "value6"
s1 = oINI.ReadKey("Section1", "key1", 10)
s2 = oINI.ReadKey("Section2", "key1", 10)
MsgBox s1
MsgBox s2
Set oINI = Nothing |
|