Convert HttpPostedFileBase to byte[]

Convert HttpPostedFileBase to byte[]

Asked on December 18, 2018 in Arrays.
Add Comment


  • 1 Answer(s)

     

    MemoryStream target = new MemoryStream();
    model.File.InputStream.CopyTo(target);
    byte[] data = target.ToArray();

    It’s easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

    For efficient purposes you could check whether the stream returned is already a MemoryStream:

    byte[] data;
    using (Stream inputStream = model.File.InputStream)
    {
        MemoryStream memoryStream = inputStream as MemoryStream;
        if (memoryStream == null)
        {
            memoryStream = new MemoryStream();
            inputStream.CopyTo(memoryStream);
        }
        data = memoryStream.ToArray();
    }
    Answered on February 21, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.