Main Site Documentation

MemoryStream ArgumentException


#1

I am having troubles reading data in chunks from a file. At second Read I get “A first chance exception of type ‘System.ArgumentException’ occurred in System.IO.dll”.

Am I missing something obvious here?

Dim stream As New MemoryStream(Resources.GetBytes(Resources.BinaryResources.MyFile))
Dim buffer(4095) As Byte
Dim i As Int32
Do While i < stream.Length
	i += stream.Read(buffer, i, buffer.Length)
	' process data from buffer here
Loop

#2

if i > 0 you try to read more bytes then the buffer can store


   i += stream.Read(buffer, i, buffer.Length-i)

but what do you you read if the buffer is smaler then your recourse


#3

I have tried your suggestion, but I still get the same error after the first read.
Correct me if i am wrong but:

  1. buffer is zero-based, so [em]buffer(4095)[/em] has 4096 elements; why should I subtract 1 from its length?
  2. you can specify buffer as large as you want, even if my resource is let’s say 4k and I specify buffer as 8k, .net will read 4k and return the number of elements it managed to read, you won’t get any errors; at least that’s how it works in full .net framework.

#4

if your buffer is 8k and your recource is 4k then
i must be 4k after the first step.
if i is still < stream.Length then i must be buffer.length after the first step,
so the buffer.length must be < stream.Length

maybe you have to set i=0 before first use


#5

Btw, my resource is 61440 bytes, so there should be 15 reads.
I have tried “Dim i As Int32 = 0”, but as expected it didn’t change anything.

Maybe you can try to put a bigger file in your project Resources section and try to replicate this issue so that we could be sure it is not happening just for me?


#6

ok i think i understand

your read the first part
process the data
you want to read the next…


i += stream.Read(buffer, 0, buffer.Length)


#7

Thanks! I forgot that it automatically seeks. Now everything is working well.