MemoryStream threw an exception of type 'System.InvalidOperationException'

63 views Asked by At

No matter what, new instances of MemoryStream in C# / .NET 8.0 keep throwing this exception:

CanRead [bool]: true
CanSeek [bool]: true
CanTimeout [bool]: false
CanWrite [bool]: true
Capacity [int]: 1000
Length [long]: 1000
Position [long]: 0
ReadTimeout [int]:
'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
WriteTimeout [int]:
'ms.WriteTimeout' threw an exception of type 'System.InvalidOperationException'

Here is the code that is being used that results in this error. Note that this code works successfully in .NET 4.6+ so why is it not working in .NET 8?

byte[] myBytes = new byte[1000];       
using (var ms = new MemoryStream(myBytes))
{
   var foobar = ms; // exception thrown here
}
1

There are 1 answers

0
HBCondo On

By adding these lines before writing to the stream, I was able to resolve this issue:

ms.Flush();
ms.Position = 0;

Source: https://stackoverflow.com/a/57082384/327066