DOCX and XLSX document corruption when retrieving from SQL
I found the following code on stackOverflow:
Public Function retreiveDoc(ByVal docFileDescription As String, _ ByVal genericID As String, _ ByVal formName As String) As String
Dim docPathandName As String = String.Empty
Using connection As SqlConnection = New SqlConnection(My.Settings.connSQL)
Dim command As Sq开发者_开发知识库lCommand = New SqlCommand( _
"SELECT fileStore_ID, fileType, imageData FROM FileStore WHERE fileDescription = " & _
"'" & docFileDescription & "'" & _
" AND generic_ID = " & "'" & genericID & "'" & _
" AND appFormName = " & "'" & formName & "'", connection)
Dim docType As String = String.Empty
'! Writes the BLOB to a file
Dim stream As FileStream
'! Streams the binary data to the FileStream object.
Dim writer As BinaryWriter
'! The size of the BLOB buffer.
'Dim bufferSize As Integer = 100
Dim bufferSize As Integer = 4096
'! The BLOB byte() buffer to be filled by GetBytes.
Dim outByte(bufferSize - 1) As Byte
'! The bytes returned from GetBytes.
Dim retval As Long
'! The starting position in the BLOB output.
Dim startIndex As Long = 0
'! The publisher id to use in the file name.
Dim fileStore_ID As Int32
'! Open the connection and read data into the DataReader.
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess)
Do While reader.Read()
fileStore_ID = reader.GetInt32(0)
docType = reader.GetString(1)
'! Create a file to hold the output.
stream = New FileStream( _
defaultDrive & "\imageData" & fileStore_ID & docType, FileMode.OpenOrCreate, FileAccess.Write)
writer = New BinaryWriter(stream)
'! Reset the starting byte for a new BLOB.
startIndex = 0
'! Read bytes into outByte() and retain the number of bytes returned.
retval = reader.GetBytes(2, startIndex, outByte, 0, bufferSize)
'! Continue while there are bytes beyond the size of the buffer.
Do While retval > 0
writer.Write(outByte)
writer.Flush()
' Reposition start index to end of the last buffer and fill buffer.
startIndex += retval
retval = reader.GetBytes(2, startIndex, outByte, 0, bufferSize)
Loop
writer.Flush()
writer.Close()
stream.Close()
Loop
reader.Close()
connection.Close()
Return (defaultDrive & "imageData" & fileStore_ID & docType)
End Using
End Function
It works great for everything except DOCX and XLSX documents. I converted the original C# to VB and maybe I missed something.
Check the writing part too for over-allocation of the buffer Byte() array. See my answer in this post and here for another example.
精彩评论