Speaking in Code

Sunday, April 15, 2007

Reading Writing Bytes at a manageable rate

I have it on good authority that this is an excellent technique for transferring bytes from one file to another:
Dim fs As FileStream = New FileStream(path, FileMode.Open, FileAccess.Read)
Dim ws As FileStream = New FileStream(path, FileMode.Append, FileAccess.Write)

Dim Buffer(102400) As Byte
Dim BytesRead As Integer
Dim Chunksize As Integer = 102400

BytesRead = fs.Read(Buffer, 0, Chunksize)

While BytesRead > 0
ws.Write(Buffer, 0, BytesRead)
BytesRead = fs.Read(Buffer, 0, Chunksize)
End While


In particular, this is superior to saving the contents of a file in a string variable if there is any chance that the total memory required to store the file might exceed the limits of available RAM.

Labels: , , ,