Converting the Uploaded File into a Byte Array with C#

This technical article was first published on 2022-12-19. Code samples reflect the library versions of that time; test them against current versions before use.
How to Convert an Uploaded File to Byte Array with C#?
Everyone who has coded in C# has done file uploads. We always perform more than one variation when uploading files. In this article, we will look at how to convert the uploaded file into byte[].
First of all, specific upload codes must be written for the platform on which the upload will be made. In this article, only the back-end codes after the file is sent to upload are available.
If we look at our method that will perform the operation immediately, it will be as follows;
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
This method accepts Stream as a parameter. In other words, it refers to the file to be loaded. We can explain an example scenario that may occur while loading the file by coding as follows;
HttpPostedFile uploadFile = HttpContext.Current.Request.Files["file"];
byte[] DOSYA = ReadFully(uploadFile.InputStream);
Thus, we convert the uploaded file into byte[]. What we do next will depend on your needs.
We wish everyone good work.
