Home > OS >  Memory stream is always closed ' cannot access a closed stream;
Memory stream is always closed ' cannot access a closed stream;

Time:07-21

trying to implement a simple memorystream like so:

        var stream = new MemoryStream();
        workbook.SaveAs(stream);

however it trips up every single time throwing this exception:

ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

and

writeTimeOut= 'stream.writeTimeOut' threw an exception of type 'System.InvalidOperationException'

every single time this happens.

things i've tried:

using (var stream = new MemoryStream())
 {
        workbook.SaveAs(stream);
        stream.Seek(0, 0);
 }

and

await using var stream = new MemoryStream();

and also :

    using (var stream = new MemoryStream())
 {
        stream.Flush();
        stream.Position = 0;
        workbook.SaveAs(stream);
        stream.Seek(0, 0);
 }

but everything yields the same result of 'Cannot access a closed Stream.'

workbook is an IXLWorkbook any ideas?

when i hover over workbook in debug it reads '{XLWorkbook(System.IO.MemoryStream)}'

i am creating my workbook as such:

        var workbook = new XLWorkbook();

        using var stream = new MemoryStream();
        workbook.SaveAs(stream);
        byte[] content = stream.ToArray();

        return workbook;

CodePudding user response:

Try this, before reading the stream :

stream.position = 0;

CodePudding user response:

use stream reader like this:

StreamReader sr = null;
try
{
    workbook.SaveAs(stream);
    sr = new StreamReader(stream);
    stream.Position = 0;
    Console.WriteLine(sr.ReadToEnd());                           
}
finally
{
    if (sr != null) sr.Dispose();
}
  • Related