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();
}
}
Try checking the resp.Content.Headers.ContentLength
property, which should contain the size of the file in bytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With