0

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?

pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63
Matias Barrios
  • 4,674
  • 3
  • 22
  • 49
  • Is this ASP.net? And if so, have you considered limiting the upload size in the web.config file [as shown here](https://stackoverflow.com/a/288675/1563833)? – Wyck May 26 '20 at 13:18
  • I do not have that file in my config. Its a RESTful API in .Net Core 2.2 – Matias Barrios May 26 '20 at 13:24
  • Does this answer your question? [Increase upload file size in Asp.Net core](https://stackoverflow.com/questions/38698350/increase-upload-file-size-in-asp-net-core) – pinkfloydx33 May 26 '20 at 13:37

1 Answers1

1

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.

Thom
  • 111
  • 1
  • 3
  • something like this using FileInfo? FileInfo info = new FileInfo(fullFilePath); //Gets the size, in bytes, of the current file. long size = info.Length; https://stackoverflow.com/a/18127628/3163418 – mapa0402 May 26 '20 at 13:26