Converting the Uploaded File into a Byte Array with C#

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.

 

Would you like to have an interview?

We help you with your business's most critical issues and opportunities. How about getting permanent change and results together?