Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArgumentOutOfRangeException when downloading file via Stream.Read

I've been struggling with a problem when downloading very big files (>2GB) on Silverlight. My application is an out-of-browser Download Manager running with elevated permissions.

When the file reaches a certain ammount of data (2GB), it throws the following exception:

System.ArgumentOutOfRangeException was caught
  Message=Specified argument was out of the range of valid values.
Parameter name: count
  StackTrace:
   in MS.Internal.InternalNetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state)
   in MS.Internal.InternalNetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   in MySolution.DM.Download.BeginResponseCallback(IAsyncResult ar)
  InnerException: 
Null

The only clue I have is this site, who shows the BeginCode implementation. This exception only occurs when count is < then 0.

My code

/* "Target" is a File object. "source" is a Stream object */

var buffer = new byte[64 * 1024];
int bytesRead;
Target.Seek(0, SeekOrigin.End); // The file might exists when resuming a download

/* The exception throws from inside "source.Read" */
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
    Target.Write(buffer, 0, bytesRead);
    _fileBytes = Target.Length;
    Deployment.Current.Dispatcher.BeginInvoke(() => { DownloadPercentual = Double.Parse(Math.Round((decimal)(_fileBytes / (_totalSize / 100)), 5).ToString()); });
}

Target.Close();
logFile.Close();

The error occurs with different kind of files, and they come from public buckets on Amazon S3. (with regular http requests).

like image 374
Dorival Avatar asked Nov 13 '22 00:11

Dorival


1 Answers

I searched a bit and it looks like this is a known limitation in Silverlight. One possible workaround is to perform the download in multiple sections, each smaller than 2GB, using the Range header.

like image 53
Badaro Avatar answered Nov 15 '22 14:11

Badaro