Cannot close stream until all bytes are written – C#
This error is raised when the position of stream or memory stream object is set at the end of stream. To resolve the issue either you can set the position to “o” as shown below.
1 2 |
MemoryStream ms = new MemoryStream(); // Your memory stream ms.Position=0; |
If this doesn’t work, you can re-create the memory stream as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
MemoryStream content =new MemoryStream(); // Your memory stream. MemoryStream ms = new MemoryStream(ReadFully(content)); // New memory stream public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; input.Seek(0, SeekOrigin.Begin); using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } |