Read/Write binary files - vb.net

I have this code which works well:
Public Function LoadBinaryFile(strFilename As String) As Byte()
Using fsSource As FileStream = New FileStream(strFilename, FileMode.Open, FileAccess.Read)
' Read the source file into a byte array.
Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {}
Dim numBytesToRead As Integer = CType(fsSource.Length, Integer)
Dim numBytesRead As Integer = 0
'tsProgressBar.Minimum = 0
'tsProgressBar.Maximum = numBytesToRead
While (numBytesToRead > 0)
' Read may return anything from 0 to numBytesToRead.
Dim n As Integer = fsSource.Read(bytes, numBytesRead, _
numBytesToRead)
' Break when the end of the file is reached.
If (n = 0) Then
Exit While
End If
numBytesRead = (numBytesRead + n)
numBytesToRead = (numBytesToRead - n)
'tsProgressBar.Value = numBytesRead
End While
numBytesToRead = bytes.Length
Return bytes
End Using
End Function
And I have this code to save the file which also works well:
Public Function SaveBinaryFile(strFilename As String, bytesToWrite() As Byte) As Boolean
Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
fsNew.Write(bytesToWrite, 0, bytesToWrite.Length)
End Using
End Function
What I am after is some help to modify the SaveBinaryFile function to implement a progress bar.
Final:
OK, I have written the function myself. Here it is:
Public Function ReadBinaryFile(strFilename As String) As Byte()
Dim position As Integer = 0
Dim bufferSize As Integer = 4096
Dim bytes() As Byte
'frmMain.tsProgressBar.Value = 0
Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open)
redim bytes((fsOpen.Length) - 1)
Do
If (position + bufferSize) > fsOpen.Length Then
fsOpen.Read(bytes, position, fsOpen.Length - position)
Exit Do
Else
fsOpen.Read(bytes, position, bufferSize)
End If
'frmMain.tsProgressBar.Value = ((position / fsOpen.Length) * 100)
'frmMain.tsProgressBar.Refresh()
Application.DoEvents()
position += bufferSize
Loop
End Using
Return bytes
End Function

My.Computer.Filesystem.ReadAllBytes("filename") reads the entire file into a byte array.
My.Computer.Filesystem.WriteAllBytes("filename", bytes, false) writes it back.

I've never tried using the Async options on FileStream but there don't seem to be any event handlers.
I would break it down into a loop, you have the total amount of bytes to write so you could loop through writing 4k at a time, update your progress bar and continue the loop.
Public Sub SaveBinaryFile(strFilename As String, bytesToWrite() As Byte)
Dim position As Integer = 0
Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
Do
Dim intToCopy As Integer = Math.Min(4096, bytesToWrite.Length - position)
Dim buffer(intToCopy - 1) As Byte
Array.Copy(bytesToWrite, position, buffer, 0, intToCopy)
fsNew.Write(buffer, 0, buffer.Length)
ProgressBar1.Value = ((position / bytesToWrite.Length) * 100)
Application.DoEvents()
position += intToCopy
Loop While position < bytesToWrite.Length
End Using
End Sub

'Or, if you are reading a file from a URL, here is a way to read the file into an array of bytes.
Dim WebRequest As Net.HttpWebRequest = Net.WebRequest.Create("http://mypage.abc.com/myfolder/MyFileName.xls")
Using WBinReader As BinaryReader = New BinaryReader(WRequest.GetResponse.GetResponseStream)
Dim file_buffer() As Byte
'10000000 is an arbitrary number, but File_Buffer will have no more
'elements than they number of bytes in the URL's file.
file_buffer = WBinReader.ReadBytes(10000000)
file_bytes =UBound(buffer)+1
End Using
Brian Jasmer

Related

How to compare bytes of array in stream which i have write it before?

I want to check if my edited stream have my bytes but the result is always failed I just can't find the wrong with my function
Public Function passbyte(ByVal filename As String, ByVal pass As String)
As Boolean
Dim passarray(0 to 2) As Byte
Dim realarray(0 To 2) As Byte
Dim result = False
Dim pos As Integer
pos = 0
If IO.File.Exists(filename) Then
Using Stream As New FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
Stream.Seek(pos, SeekOrigin.Begin)
passarray = System.Text.Encoding.ASCII.GetBytes(pass)
Stream.Write(passarray, 0, 3)
Stream.Read(realarray, 0, 3)
If realarray(0) = passarray(0) and realarray(1) = passarray(1) and realarray(2) = passarray(2) Then
result = True
MsgBox("Success")
Else
result = False
MsgBox("Failed")
End If
stream.close()
End Using
End If
Return result
End Function
Can't you do this without the loops?
If pass = My.Computer.FileSystem.ReadAllText(filename) Then

VB.NET stream read calculate crc32

I am reading files using stream reader and writer with a buffer. Is it possible to calculate the crc32 checksum of the file at the same time so that it would evaluate the buffer during each iteration, and the result would be the crc32 of the complete file, instead of having to read teh file twice? Here is the code:
Public Function APPEND_FILE_TO_FILE(ByVal SOURCE_FILE As String, ByVal DESTINATION_FILE As String)
Dim nn As New FileInfo(SOURCE_FILE)
Dim BUFFER(BUFFER_SIZE) As Byte
Dim BYTES_READ As Long = 0
Using inFile As New System.IO.FileStream(SOURCE_FILE, IO.FileMode.Open, IO.FileAccess.Read)
Using outFile As New System.IO.FileStream(DESTINATION_FILE, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
Do
BYTES_READ = inFile.Read(BUFFER, 0, BUFFER_SIZE)
TOTAL_PROCESSED_DATA += BYTES_READ ' GUI related
outFile.Write(BUFFER, 0, BYTES_READ)
Loop While BYTES_READ > 0
End Using
End Using
End Function
CRC32 function:
Public Function GetCRC32(ByVal sFileName As String) As String
Try
Dim FS As FileStream = New FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
Dim CRC32Result As Integer = &HFFFFFFFF
Dim Buffer(4096) As Byte
Dim ReadSize As Integer = 4096
Dim Count As Integer = FS.Read(Buffer, 0, ReadSize)
Dim CRC32Table(256) As Integer
Dim DWPolynomial As Integer = &HEDB88320
Dim DWCRC As Integer
Dim i As Integer, j As Integer, n As Integer
'Create CRC32 Table
For i = 0 To 255
DWCRC = i
For j = 8 To 1 Step -1
If (DWCRC And 1) Then
DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
DWCRC = DWCRC Xor DWPolynomial
Else
DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
End If
Next j
CRC32Table(i) = DWCRC
Next i
'Calcualting CRC32 Hash
Do While (Count > 0)
For i = 0 To Count - 1
n = (CRC32Result And &HFF) Xor Buffer(i)
CRC32Result = ((CRC32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
CRC32Result = CRC32Result Xor CRC32Table(n)
Next i
Count = FS.Read(Buffer, 0, ReadSize)
Loop
Return Hex(Not (CRC32Result))
Catch ex As Exception
Return ""
End Try
End Function
The above code leaves the file being parsed [open] and cannot be renamed or deleted.
The line:
Count = FS.Read(Buffer, 0, ReadSize)
Loop
Return Hex(Not (CRC32Result))
Should Be:
Count = FS.Read(Buffer, 0, ReadSize)
Loop
FS.Close
Return Hex(Not (CRC32Result))
Then the file can be manipulated again.

Read MemoryStream - load image \ byte and read it

ok i have image that i bind info in it and i want to read the info
now from file (FileStream) its work
but i want to do it not from file so i need to use MemoryStream
here the example that work and how i do it now how i make it work with MemoryStream (with byte = My.Resources or PictureBox1.image)
Using FS As New IO.FileStream(image, IO.FileMode.Open)
FS.Seek(0, IO.SeekOrigin.End)
While Not FS.ReadByte = Asc("|")
FS.Position -= 2
End While
Dim s As String = Nothing
While Not FS.Position = FS.Length - 4
s &= Chr(FS.ReadByte.ToString)
End While
Dim Ext As String = Nothing
FS.Seek(0, IO.SeekOrigin.End)
While Not FS.ReadByte = Asc("*")
FS.Position -= 2
End While
While Not FS.Position = FS.Length
Ext &= Chr(FS.ReadByte.ToString)
End While
FS.Seek(FS.Length - ((s.Length + s) + 5), IO.SeekOrigin.Begin)
While Not FS.Position = FS.Length - (s.Length + 5)
Dim Data As Byte() = New Byte(FS.Position) {}
FS.Read(Data, 0, Data.Length)
FS.Close()
End While
at the end save the byte to file
i try to use it like this
Using FS As New IO.MemoryStream(image) 'image = byte()
but not work
how i can do it read it again in memory
thanks
This will convert a ByteArray to MemoryStream to Image
Public Function byteArrayToImage(byteArrayIn As Byte()) As Image
Dim ms As New MemoryStream(byteArrayIn)
Dim returnImage As Image = Image.FromStream(ms)
Return returnImage
End Function

Read/Write binary files overflow

I am wanting some help with some code please. Here is my code:
Public Function ReadBinaryFileLarge(strFilename As String) As Byte()
Dim position As Integer = 0
Dim bufferSize As Integer = 4096
Dim bytes() As Byte
Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open)
ReDim bytes((fsOpen.Length) - 1)
Do
If (position + bufferSize) > fsOpen.Length Then
fsOpen.Read(bytes, position, fsOpen.Length - position)
Exit Do
Else
fsOpen.Read(bytes, position, bufferSize)
End If
position += bufferSize
Application.DoEvents()
Loop
End Using
Return bytes
End Function
Public Sub SaveBinaryFileLarge(strFilename As String, bytesToWrite() As Byte)
Dim position As Integer = 0
Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
Do
Dim intToCopy As Integer = Math.Min(4096, bytesToWrite.Length - position)
Dim buffer(intToCopy - 1) As Byte
Array.Copy(bytesToWrite, position, buffer, 0, intToCopy)
fsNew.Write(buffer, 0, buffer.Length)
position += intToCopy
Application.DoEvents()
Loop While position < bytesToWrite.Length
End Using
End Sub
My problem is that with large files, the byte array cannot be declared that large. I am needing to load it into a byte array to do some encryption work on the byte array. I am playing around with this code:
Public Function ReadBinaryFileTest(strFilename As String) As Byte()()
Const SIZE As Integer = &H1000 '4096 <-experiment with this value
Dim bytes()() As Byte
Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open, FileAccess.Read, FileShare.Read, SIZE)
Dim ubound = (fsOpen.Length / SIZE) - 1
bytes = new byte(ubound)()
Dim read As Integer = 0
For index As Integer = 0 To ubound
bytes(index) = New Byte(SIZE - 1)
read = fsOpen.Read(bytes(index), 0, SIZE)
If read <> SIZE Then
Array.Resize(bytes(index), read) 'this should only happen once if at all
End If
Next
End Using
Return bytes
End Function
However I am getting these errors:
bytes = new byte(ubound)()
'{' expected
and
bytes(index) = New Byte(SIZE - 1)
Type 'Byte' has no constructors.
Is this the correct way to go about this problem? If not, how should I attack it?
You have to use ReDim,
ReDim bytes(ubound-1)
Or
bytes = New Byte(ubound)() {}

Sending a HttpRequest back down a HttpRequest (proxy)

I have the following code:
With context.Response
Dim req As HttpWebRequest = WebRequest.Create("http://www.Google.com/")
req.Proxy = Nothing
Dim res As HttpWebResponse = req.GetResponse()
Dim Stream As Stream = res.GetResponseStream
.OutputStream.Write(Stream, 0, Stream.Length)
End With
Sadly, the above code doesn't work. I need to take the RequestStream and put it into the OutputStream from the context.Response.
Any ideas?
Write takes a byte array, whereas you are passing it a stream.
Try reading from the stream and getting all the data before writing it back.
First, read the data into an intermediate byte array (Taken from here):
Dim bytes(Stream.Length) As Byte
Dim numBytesToRead As Integer = s.Length
Dim numBytesRead As Integer = 0
Dim n As Integer
While numBytesToRead > 0
' Read may return anything from 0 to 10.
n = Stream.Read(bytes, numBytesRead, 10)
' The end of the file is reached.
If n = 0 Then
Exit While
End If
numBytesRead += n
numBytesToRead -= n
End While
Stream.Close()
Then write it to the output stream:
.OutputStream.Write(bytes, 0, Stream.Length)