0

enter image description hereWhenever converting the imagefile into bytes we got an error like

cannot access a closed file

Please help me in order to overcome this

private byte[] ConvertToBytes(HttpPostedFileBase file)
{
    byte[] imageBytes = null;
    BinaryReader reader = new BinaryReader(file.InputStream);

    imageBytes = reader.ReadBytes((int)file.ContentLength);

    return imageBytes;
}

2 Answers2

1

Use a BinaryReader object to return a byte array from the stream like:

byte[] fileData = null;
var binaryReader = new BinaryReader(Request.Files[0].InputStream);
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
John H
  • 21
  • 3
0

In case it can help:

try
{
    using (var bitmap = new System.Drawing.Bitmap(file.InputStream))
    {
        using (var memoryStream = new MemoryStream())
        {
             bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
             return memoryStream.ToArray();
        }
    }
}
catch (Exception)
{
    return null;
}
finally
{
    postedFile.InputStream.Position = 0;
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Hossein
  • 3,083
  • 3
  • 16
  • 33