VBS、ASP 利用 Adodb.Stream 读写二进制文件

    根据前几篇 UTF-8 编码和转换的文章代码成果,组装了一个 VBS 和 ASP 读写二进制文件的模块,以便于 Base64 和 MD5 需要进行文件编码时使用,或其它需要用到二进制数据文件时使用:

public function Varr2hexstr(a)  '-------转换 Variant 数组为十六进制字符串
	dim i,S
    For i = 0 To UBound(a)
        S=S & Right("00" & Hex(a(i)), 2)
    Next
    Varr2hexstr=S
End Function
 
public function HexStr2ByteArr(S) '-------转换十六进制字符串为 Bytes 数组(真,可写入ADODB.Stream.Write)
	Dim xmldoc, node, bytes
	Set xmldoc = CreateObject("Msxml2.DOMDocument") 
	Set node = xmldoc.CreateElement("binary") 
	node.DataType = "bin.hex" 
	node.Text = S
	bytes = node.NodeTypedValue 
	'WScript.Echo VarType(bytes), TypeName(bytes),"bytes"
    set xmldoc=nothing
    set node=nothing	
	HexStr2ByteArr=bytes
End Function

public Function Varr2ByteArr(v)
	Varr2ByteArr=HexStr2ByteArr(Varr2hexstr(V))
End Function

public Function ByteArr2Varr(b)
	dim i,v
	redim v(ubound(b))
	for i=0 to ubound(b)
		v(i)=ascb(midb(b,i+1,1))
	next
	ByteArr2Varr=v
end Function

public function saveFileByte(data,recfilen)
	dim fxt,txt,Astream
    set Astream=CreateObject("Adodb.Stream") 'asp Server.CreateObject("Adodb.Stream")
    Astream.type=1  '1 bin,2 txt
    Astream.Mode = 3'    adModeReadWrite =3 
    Astream.open
    Astream.Position =0 '装载文件时设置为Assp
    Astream.Write data
    'msgbox recfilen
    Astream.SaveToFile recfilen,2
	' "F:\temp\a.jpg",2 
    Astream.close
	set Astream=Nothing
end function

public Function ReadFileByte(FileUrl) 
    Dim b,stm
    Set stm = CreateObject("Adodb.Stream") 
    stm.Type = 1 
    stm.mode = 3 
    stm.Open
	'stm.charset = CharSet
    stm.loadfromfile FileUrl 
    b = stm.read()
    stm.Close 
    Set stm = Nothing 
    ReadFileByte = b
End Function

使用范例:

dim apppath
apppath=left(wscript.scriptfullname,instrrev(wscript.scriptfullname,"\")-1)
	call betyx
	
sub betyX()
	dim s,b,f1,f2,i
	f1=apppath & "\utf8.txt"
	f2=apppath & "\utf8_2.bin"
	b=ReadFileByte(f1)
	'WScript.Echo VarType(b), TypeName(b),"b"
	s=ByteArr2Varr(b)
	for i=0 to ubound(s)
		s(i)=s(i)+1
	next	
	'msgbox s(26)
	call saveFileByte(Varr2ByteArr(s),f2)
end sub

将一个 UTF-8 编码的文本文件读入,每字节加 1 后,再写回新文件,更多用途请自行扩展。

此记!

你可能感兴趣的:(VB.研究心得,源码.VB,VB.日记,vbscript,asp,读写二进制文件,Adodb.Stream)