I have this code to upload an image file in my c# restful api :
using(Streamer reader = new StreamerReader(req.Bindfile().Result.OpenReadStream())) {
request.Data.Image = Encoding.ASCII.GetBytes(reader.ReadToEnd());
}
I know I am slurping the file in one shot, but I would like to know the "right way" to modify this code so it rejects a file when it is bigger than 10 Megabytes.
I am inspecting the methods of reader instance and I cannot find anything useful other than read the file by blocks and just keep track of how many bytes I have read until that point.
Is that correct? Can someone help me to do this the C# way?
You can check the amount of bytes present in the stream and convert them to MB like so: amountOfBytes / (1024 * 1024f). You can then check if the amount is above your threshold, in your case 10, and take action accordingly.