Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2813
  • Last Modified:

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];
                    else
                        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);

                    client.BeginUploadAsync(req);



                }
            }
0
boukaka
Asked:
boukaka
  • 2
1 Solution
 
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...
0
 
lenordisteCommented:
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.
0
 
abelallenCommented:
Hi,

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.


Regards,
Abel Allen
0
 
boukakaAuthor Commented:
Ah I see, thank you!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now