Filestream " Offset and length were out of bounds.. "

I'm getting an error when reading files - System.ArgumentException: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. Can anyone tell from this what I should be changing? it breaks on read = fs.Read(buffer, 0, Utility.chunkSize);

 using (FileStream fs = this.File.OpenRead())
                    //get full hash first.
                    this.FileLength = fs.Length;

                    //setup progress bar.
                    this.Steps = (int)(this.FileLength / (long)Utility.chunkSize);
                    this.uxProgress.Minimum = 0;
                    this.uxProgress.Maximum = this.Steps;

                    int read = 0;
                    byte[] buffer = null;

                    if (fs.Length <= Utility.chunkSize)
                        buffer = new byte[(int)fs.Length];
                        buffer = new byte[Utility.chunkSize];

                    read = fs.Read(buffer, 0, Utility.chunkSize);

                    this.FilePosition += read;

                    req.Chunk = buffer;
                    req.ChunkSize = buffer.Length;
                    req.Hash = Utility.GetSHA256Hash(buffer);


Who is Participating?
lenordisteConnect With a Mentor Commented:
this line:
     read = fs.Read(buffer, 0, Utility.chunkSize);
should be:
     read = fs.Read(buffer, 0, buffer.Length);

in order to ensure you never try to put more data in your buffer than your buffer's actual size.
boukakaAuthor Commented:
I just noticed this only happens when a file is smaller than Utility.chunkSize (which is set to 102400), I can set it to something like (10000) but I'd rather fix the code to work no matter what size the file is...

You misjudged the parameter values it seems...

It must be like this...
read=fs.Read(buffer, Index, bufferSize)
where you can utilize the Length property of the array to retrieve the maximum capacity of the array.

Abel Allen
boukakaAuthor Commented:
Ah I see, thank you!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.