2011-05-19 68 views

回答

3

ADODB流對象是VBScript唯一的本地讀取二進制流的方法。如果禁用ADODB,則需要安裝其他第三方組件以提供相同的功能。

6

一年前我有類似的問題。我們知道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

3

它可以讀取所有字節加在一起:基於Luc125

Set FS = CreateObject("Scripting.FileSystemObject") 
Set fil = FS.GetFile(filename) 
fpga = fil.OpenAsTextStream().Read(file.Size) 
5

和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 

寫功能

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 
+0

你需要這條線嗎? 'Dim oTxtStream:Set oTxtStream = oFSO.createTextFile(strPath)' – 2015-07-07 06:54:27

+1

該行假設檢查文件的寫入權限。 如果您刪除它,在某些情況下腳本可能會崩潰。 – n3rd4i 2015-08-11 05:01:35