Vbscript实现编码转化-加入了自动check当前编码的函数
在QTP中用ExecuteFile语句加载vbs文件的时候,经常会报错,原因是vbs的编码类型不是ANSI, 其实只要vbs在QTP中编辑过, 它的编码格式就自动变成Unicode类型,不是这是不是QTP的一个bug.以下的方法很好的解决了这个问题, 可以在QTP加载vbs之前,遍历所有的vbs文件,从而保证其格式正确.
注: ANSI就是GB2312.
Call ConvertCode("C:\Documents and Settings\Administrator\桌面\Test\JayYang_TestCodeConvert.vbs", "GB2312")
'-------------------------------------------------
'Function Name:ConvertCode(FileUrl, TargetCode)
'Description: Convert file to specified code format
'Parameter:FileUrl-File path; TargetCode-Code format(utf-8,gb2312, unicode)
'----------------------------------------------------
Function ConvertCode(FileUrl, TargetCode)
Dim SourceCode
SourceCode = CheckCode(FileUrl)
If StrComp(SourceCode, TargetCode) <> 0 Then
Call WriteToFile(FileUrl, ReadFile(FileUrl, SourceCode), TargetCode)
End If
End Function
'-------------------------------------------------
'Function Name:CheckCode(FileUrl)
'Description: Check the code format of specified file
'Parameter:FileUrl-File path
'----------------------------------------------------
Function CheckCode(FileUrl)
Dim slz
Set slz = CreateObject("Adodb.Stream")
slz.Type = 1
slz.Mode = 3
slz.Open
slz.Position = 0
slz.Loadfromfile FileUrl
Bin=slz.read(2)
If AscB(MidB(Bin,1,1))=&HEF and AscB(MidB(Bin,2,1))=&HBB Then
Codes="UTF-8"
ElseIf AscB(MidB(Bin,1,1))=&HFF and AscB(MidB(Bin,2,1))=&HFE Then
Codes="Unicode"
Else
Codes="GB2312"
End if
slz.Close
Set slz = Nothing
CheckCode = Codes
End Function
'-------------------------------------------------
'Function Name:ReadFile(FileUrl, CharSet)
'Description: User AdoDb.Stream object to read specified code format file
'Parameter:FileUrl-File path;CharSet-Code format(utf-8,gb2312, unicode)
'----------------------------------------------------
Function ReadFile(FileUrl, CharSet)
Dim Str
Set stm = CreateObject("Adodb.Stream")
stm.Type = 2
stm.mode = 3
stm.charset = CharSet
stm.Open
stm.loadfromfile FileUrl
Str = stm.readtext
stm.Close
Set stm = Nothing
ReadFile = Str
End Function
'-------------------------------------------------
'Function Name:WriteToFile(FileUrl, Str, CharSet)
'Description: User AdoDb.Stream object to write all kind of format file
'Parameter:FileUrl-File path;Str-File content;CharSet-Code format(utf-8,gb2312, unicode)
'----------------------------------------------------
Function WriteToFile(FileUrl, Str, CharSet)
Set stm = CreateObject("Adodb.Stream")
stm.Type = 2
stm.mode = 3
stm.charset = CharSet
stm.Open
stm.WriteText Str
stm.SaveToFile FileUrl, 2
stm.flush
stm.Close
Set stm = Nothing
End Function 非常好哦!!!
我的这个文件 ,也是使用编码转换函数将文件编码转换成UTF-8,但是显示的仍然是乱码。 好贴,沉了2年了,居然都被你挖出来……
页:
[1]