November 20th, 2012, 09:57 AM
How to read bytes in chunks to avoid out of memory exception? Or something else...
after searching and trying to find a solution for 2 days i finnaly decided to post here to ask for help...
I have a code to read and write bytes of a file (like an hex editor) working very good taken from here: http://www.novahq.net/forum/showthread.php?t=42592
Here goes the code:
This is working very good, BUT only with small/medium size files. If i try to load a 512MB or a bigger file i will get "System.OutOfMemoryException" error.
Public Class Form1
Private Shared Function HexStringToByteArray(ByRef strInput As String)
Dim length As Integer
Dim bOutput As Byte()
Dim c(1) As Integer
length = strInput.Length / 2
ReDim bOutput(length - 1)
For i As Integer = 0 To (length - 1)
For j As Integer = 0 To 1
c(j) = Asc(strInput.Chars(i * 2 + j))
If ((c(j) >= Asc("0")) And (c(j) <= Asc("9"))) Then
c(j) = c(j) - Asc("0")
ElseIf ((c(j) >= Asc("A")) And (c(j) <= Asc("F"))) Then
c(j) = c(j) - Asc("A") + &HA
ElseIf ((c(j) >= Asc("a")) And (c(j) <= Asc("f"))) Then
c(j) = c(j) - Asc("a") + &HA
bOutput(i) = (c(0) * &H10 + c(1))
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim myFile As String = "..\..\Test.jpg"
Dim myBytes As Byte() =
Dim txtTemp As New System.Text.StringBuilder()
For Each myByte As Byte In myBytes
RichTextBox1.Text = txtTemp.ToString()
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim myFile As String = "..\..\Test2.jpg"
Dim myBytes As Byte() = HexStringToByteArray(RichTextBox1.Text)
My.Computer.FileSystem.WriteAllBytes(myFile, myBytes, False)
I know that in order to make this work (read bigger files without error) i have to read files in small pieces (or chunks whatever you wanna name it), or maybe read it byte by byte i suppose...
The only problem is that i couldn't find a way to do it. I did find some codes but for some reason i wasn't able to make that codes work
I apreciate if someone could give me a push on this.
...However, i've thinking and maybe i don't need to read the whole file because i just need to add some bytes to the end of the file and then remove those again.
I'll try to explain what i need:
I only need to add this "504B0506000000000000000000000000000000000000" bytes at the end of a zip in onder do blind/hide contents of zip and then i need to read in again and remove those bytes.
a) Append bytes to the end of file
b) Remove those bytes again
This sounds really simple but from all codes and examples i have found i couldn't adapt them to my code.
Tags for this Thread
Click Here to Expand Forum to Full Width