'System.ObjectDisposedException: 'Cannot access a closed Stream.' in IFormFile.CopyTo
I have a situation where I need to create the FormFile from an image and then I need back MemoryStream from FormFile. The MemoryStream from a file is in some other place. I have just made this as a sample to produce the issue.
private IFormFile ReturnFormFile(Image image, string thumbnailName)
{
IFormFile file = null;
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
file = new FormFile(ms, 0, ms.Length, "name", thumbnailName);
ms.Seek(0, SeekOrigin.Begin);
}
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
{
file.CopyTo(memStream);// System.ObjectDisposedException: 'Cannot access a closed Stream.'
Byte[] fileData = memStream.ToArray();
}
return file;
}
Any suggestions please.
Solution 1:[1]
Try this way:
private IFormFile ReturnFormFile(Image image, string thumbnailName)
{
IFormFile file = null;
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
file = new FormFile(ms, 0, ms.Length, "name", thumbnailName);
ms.Seek(0, SeekOrigin.Begin);
using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
{
file.CopyTo(memStream);// System.ObjectDisposedException: 'Cannot access a closed Stream.'
Byte[] fileData = memStream.ToArray();
}
return file;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MD. RAKIB HASAN |
