MemoryStream 引发了“System.InvalidOperationException”类型的异常

问题描述 投票:0回答:1

无论如何,C# / .NET 8.0 中

MemoryStream
的新实例都会抛出此异常:

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'

这是正在使用的导致此错误的代码。请注意,此代码在 .NET 4.6+ 中可以成功运行,那么为什么它不能在 .NET 8 中运行呢?

byte[] myBytes = new byte[1000];       
using (var ms = new MemoryStream(myBytes))
{
   var foobar = ms; // exception thrown here
}
memorystream c#-8.0
1个回答
0
投票

通过在写入流之前添加这些行,我能够解决此问题:

ms.Flush(); ms.Position = 0;
来源:

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

© www.soinside.com 2019 - 2024. All rights reserved.