I'm having an issue when attempting to extract .xls files that are stored as BLOBs from SQL SERVER 2000. The following works perfectly for .txt and .doc files. However, when I download .xls files, they become corrupted. I'm thinking that it has to do with the fact that I'm using a BinaryWriter. Any suggestions?
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim fs As FileStream
Dim bw As BinaryWriter
Dim bufferSize As Integer = 500
Dim outbyte(bufferSize - 1) As Byte
Dim retval As Long
Dim startIndex As Long = 0
Dim pub_id As String = ""
' Read record
Dim reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
reader.Read()
fs = New FileStream(NetDirectory & FileName, _
FileMode.OpenOrCreate, FileAccess.Write)
bw = New BinaryWriter(fs)
startIndex = 0
retval = reader.GetBytes(0, 0, outbyte, 0, bufferSize)
' Continue reading and writing while there are bytes beyond the size of the buffer.
Do While retval = bufferSize
bw.Write(outbyte)
bw.Flush()
' Reposition the start index to the end of the last buffer and fill the buffer.
startIndex += bufferSize
'(The zero-based column ordinal, The index within the field from which to begin the read operation,
' The buffer into which to read the stream of bytes, The index for buffer to begin the read operation,
' The maximum length to copy into the buffer)
retval = reader.GetBytes(0, startIndex, outbyte, 0, bufferSize)
Loop
bw.Write(outbyte, 0, retval - 1)
bw.Flush()
bw.Close()
fs.Close()
reader.Close()
If conn.State = ConnectionState.Open Then
conn.Close()
' Dispose connection
conn.Dispose()
End If
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim fs As FileStream
Dim bw As BinaryWriter
Dim bufferSize As Integer = 500
Dim outbyte(bufferSize - 1) As Byte
Dim retval As Long
Dim startIndex As Long = 0
Dim pub_id As String = ""
' Read record
Dim reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)
reader.Read()
fs = New FileStream(NetDirectory & FileName, _
FileMode.OpenOrCreate, FileAccess.Write)
bw = New BinaryWriter(fs)
startIndex = 0
retval = reader.GetBytes(0, 0, outbyte, 0, bufferSize)
' Continue reading and writing while there are bytes beyond the size of the buffer.
Do While retval = bufferSize
bw.Write(outbyte)
bw.Flush()
' Reposition the start index to the end of the last buffer and fill the buffer.
startIndex += bufferSize
'(The zero-based column ordinal, The index within the field from which to begin the read operation,
' The buffer into which to read the stream of bytes, The index for buffer to begin the read operation,
' The maximum length to copy into the buffer)
retval = reader.GetBytes(0, startIndex, outbyte, 0, bufferSize)
Loop
bw.Write(outbyte, 0, retval - 1)
bw.Flush()
bw.Close()
fs.Close()
reader.Close()
If conn.State = ConnectionState.Open Then
conn.Close()
' Dispose connection
conn.Dispose()
End If