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 後,再寫回新文件,更多用途請自行擴展。

此記!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章