如何以编程方式修复损坏的 docx 文件(添加丢失的字节)

How to fix corrupted docx files programmatically (adding missing bytes)

我正在尝试修复 classic asp 中的一大批损坏的 .docx 文件。

(文件末尾缺少字节 - 如 中详述)。

当我在 Sublime 中查看文件时(以十六进制视图显示),可以通过在文件末尾添加 0000 来修复损坏。

但我正在努力以编程方式将这 4 个零添加到末尾。

我正在尝试使用 cByteArray class,它的用法是这样的:

With oByte
    Call .AddBytes(LoadBytes(sFilePath))
    Call .AddBytes(HOW DO I GET THE BYTE VALUE OF 0000 HERE?)
    lngBytes = .BytesTotal
    ByteArray = .ReturnBytes
End With

Call SaveBytesToBinaryFile(ByteArray, sNewFilePath)

我不知道如何将 0000 值输入到 .AddBytes() 方法中。

我该怎么做?我有点超出我的深度,不确定我是否以正确的方式接近这个。


在我的无知中,这是我尝试过的:


Redimming ByteArray 将多余的字节留空(因为我认为 0000 代表空值)。

这似乎根本没有改变文件。新保存的文件与旧文件相同。

With oByte
    Call .AddBytes(LoadBytes(sFilePath))
    ByteArray = .ReturnBytes
End With

arrayLength = ubound(ByteArray)
redim ByteArray(arrayLength + 2)

Call SaveBytesToBinaryFile(ByteArray, sNewFilePath)

0000 从十六进制转换为字节并将其添加到损坏的文件字节中。

同样,这似乎根本没有改变文件。

dim k, hexString, str, stream, byteArrToAdd
hexString = "000000"
For k = 1 To Len(hexString) Step 2
 str = str & Chr("&h" & Mid(hexString, k, 2))
response.write "<hr />" & str & "<hr />"
Next

Set stream = CreateObject("ADODB.Stream")
With stream
 .Open
 .Type = 2       ' set type "text"
 .WriteText str  
 .Position = 0
 .Type = 1       ' change type to "binary"
 byteArrToAdd = .Read 
 .Close
End With
set stream = nothing

With oByte
    Call .AddBytes(LoadBytes(sFilePath))
    Call .AddBytes(byteArrToAdd)
    ByteArray = .ReturnBytes
End With

Call SaveBytesToBinaryFile(ByteArray, sNewFilePath)

获取损坏文件的最后一个字节,并在重新调暗 ByteArray 后将其添加到 2 个新值。

这似乎也根本没有改变文件!!

With oByte
    Call .AddBytes(LoadBytes(sFilePath))
    ByteArray = .ReturnBytes
End With


arrayLength = ubound(ByteArray)
finalByte = ByteArray(arrayLength)
redim ByteArray(arrayLength + 2)
ByteArray(arrayLength + 1) = finalByte
ByteArray(arrayLength + 2) = finalByte

Call SaveBytesToBinaryFile(ByteArray, sNewFilePath)

您可以在用户定义的转换(字符串到字节 ())函数的帮助下使用二进制文件流,如下所示。

Function GetBytesOf(str) 'returns bytes of given string
    With CreateObject("Adodb.Stream")
        .Type = 2 'text
        .Charset = "x-ansi" 
        .Open
        .WriteText str
        .Position = 0
        .Type = 1 'binary
        GetBytesOf = .Read 'returns Byte()
        .Close
    End With
End Function

Dim patch
patch = GetBytesOf(Chr(0) & Chr(0)) 'equals to WORD 0000

With CreateObject("Adodb.Stream")
    .Type = 1 'binary
    .Open
    .LoadFromFile sFilePath
    'move cursor to the end of file
    .Position = .Size
    .Write patch
    .SaveToFile sNewFilePath, 2 '2 for overwrite if exists
    .Close
End With