Search code examples
silverlightsilverlight-4.0downloadwebclientsilverlight-oob

Why would WebClient.OpenReadAsync return a e.Result of zero length if download is successful?


Using the following code (from a Silverlight 4 OOB app) I'm getting a result stream with a size of zero even though it takes the time to download the whole file (900+MB) and no error is reported. Fiddler also says the whole file was downloaded.

The handler on progress changed (although not shown below) is hit and reports an increase in download percentage.

This works with smaller files (10MB).

var wc = new WebClient();
wc.OpenReadCompleted += DownloadWholeFileOpenReadCompleted;
wc.DownloadProgressChanged += DownloadWholeFileDownloadProgressChanged;

wc.OpenReadAsync(new Uri(movie.DownloadUrl, UriKind.Absolute));


private static void DownloadWholeFileOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        return; // this is not hit
    }

    if (e.Error != null)
    { 
        return; // this is not hit
    }

    using (var fs = new FileStream(tempFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
    {
        var buffer = new byte[4096];
        int bytesRead;

        // <snip />

        // e.Result.Length this equals 0

        while ((bytesRead = e.Result.Read(buffer, 0, buffer.Length)) != 0)
        {
            fs.Write(buffer, 0, bytesRead);
        }

        fs.Close();
    }

    // <snip />
}

Any ideas?


Solution

  • Apparently, there is a "known issue" with using WebClient and very large files. In some cases this may be linked to issues with the Content-Length not being set by the server.

    Based on the data captured via Fiddler2, the header is being set correctly.
    I am therefore assuming that this is not the cause of my specific issue.

    Apparently, this issue does not exist with HttpWebRequest, so I'll look at changing to use that instead.