Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient: limit response (downloaded file) size while using HttpResponseMessage.Content.ReadAsStreamAsync()

I am looking for a way to police the size of a downloaded file, while using the following code:

    var client = new HttpClient();

    HttpResponseMessage resp = await client.GetAsync(mediaUri, HttpCompletionOption.ResponseHeadersRead);

    using (var fileStream = File.Create(outputPath))
    {
        using (var httpStream = await resp.Content.ReadAsStreamAsync())
        {
            httpStream.CopyTo(fileStream);
            fileStream.Flush();
        }
    }

How do I prevent download of files larger than predefined size?

Edit:

Before the answers below came in, I resorted to replacing CopyTo with this. I am putting it here to maybe weight against the ProgressMessageHandler from the answers below:

            using (var fileStream = File.Create(outputPath))
            {
                using (var httpStream = await resp.Content.ReadAsStreamAsync())
                {
                    // instead of httpStream.CopyToAsync(fileStream);
                    byte[] buffer = new byte[65536];
                    while (true)
                    {
                        int read = await httpStream.ReadAsync(buffer, 0, buffer.Length, ct);
                        if (read <= 0)
                            break;

                        // do the policing here

                        await fileStream.WriteAsync(buffer, 0, read);
                    }
                    fileStream.Flush();
                }
            }
like image 583
G. Stoynev Avatar asked Oct 16 '25 15:10

G. Stoynev


1 Answers

Try checking the resp.Content.Headers.ContentLength property, which should contain the size of the file in bytes.

like image 151
Richard Deeming Avatar answered Oct 18 '25 05:10

Richard Deeming