我之前用ADODB.Stream来读取和写入二进制文件就是这个链接
如何在VBscript中使用ADODB.stream连接二进制文件
它工作正常唯一的问题是在Windows 2003服务器上禁用ADODB.stream,
还有另一种方法我可以在二进制模式下读取3个文件并将它们连接起来或将它们存储在VBscript中的一个文件中
谢谢Jp
小智 7
根据Luc125和Alberto,这里提供了2个经过重做和简化的功能:
读取功能
Function readBinary(strPath)
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFile: Set oFile = oFSO.GetFile(strPath)
If IsNull(oFile) Then MsgBox("File not found: " & strPath) : Exit Function
With oFile.OpenAsTextStream()
readBinary = .Read(oFile.Size)
.Close
End With
End Function
Run Code Online (Sandbox Code Playgroud)
写功能
Function writeBinary(strBinary, strPath)
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
' below lines pupose: checks that write access is possible!
Dim oTxtStream
On Error Resume Next
Set oTxtStream = oFSO.createTextFile(strPath)
If Err.number <> 0 Then MsgBox(Err.message) : Exit Function
On Error GoTo 0
Set oTxtStream = Nothing
' end check of write access
With oFSO.createTextFile(strPath)
.Write(strBinary)
.Close
End With
End Function
Run Code Online (Sandbox Code Playgroud)
一年前我遇到过类似的问题.我们知道TextStream对象适用于ANSI或Unicode文本数据,而不是二进制数据; 如果流是二进制的,它们的.readAll()方法会产生损坏的输出.但有解决方法.将字符逐个读入数组可以正常工作.这应该允许您将二进制数据读入VB字符串,并将其写回磁盘.当进一步操作这样的二进制字符串时,不要忘记某些操作可能导致断字符串,因为它们仅用于文本.我总是将二进制字符串转换为整数数组,然后再使用它们.
Function readBinary(path)
Dim a
Dim fso
Dim file
Dim i
Dim ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.getFile(path)
If isNull(file) Then
MsgBox("File not found: " & path)
Exit Function
End If
Set ts = file.OpenAsTextStream()
a = makeArray(file.size)
i = 0
' Do not replace the following block by readBinary = by ts.readAll(), it would result in broken output, because that method is not intended for binary data
While Not ts.atEndOfStream
a(i) = ts.read(1)
i = i + 1
Wend
ts.close
readBinary = Join(a,"")
End Function
Sub writeBinary(bstr, path)
Dim fso
Dim ts
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set ts = fso.createTextFile(path)
If Err.number <> 0 Then
MsgBox(Err.message)
Exit Sub
End If
On Error GoTo 0
ts.Write(bstr)
ts.Close
End Sub
Function makeArray(n) ' Small utility function
Dim s
s = Space(n)
makeArray = Split(s," ")
End Function
Run Code Online (Sandbox Code Playgroud)
ADODB 流对象是 VBScript 读取二进制流的唯一本机方法。如果禁用 ADODB,您将需要安装一些其他第三方组件才能提供相同的功能。
| 归档时间: |
|
| 查看次数: |
48909 次 |
| 最近记录: |