像写入文件一样写入流,但实际上写入对象
我正在尝试将流写入内存而不是文件。我尝试这样做:
Stream stream = new MemoryStream();
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
return stream;
但是当我在应该写入流后查看流时,它说“Length ='stream.Length'抛出了'System.ObjectDisposeException'类型的异常”
I am trying write a stream to the ram instead of a file. I tried doing this:
Stream stream = new MemoryStream();
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
return stream;
But when I look at the stream after I have supposedly written to it it is saying "Length = 'stream.Length' threw an exception of type 'System.ObjectDisposedException'"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在获取数据之前不要关闭流,并且不返回流而是返回流的内容:
Don't close the stream before getting the data, and don't return the stream but the content of the stream:
您正在调用
stream.Close()
,这与在流上调用Dispose()
完全相同。只要删除那行代码就可以了。基本上,您需要在返回时将
MemoryStream
保持打开状态。另一方面,根据您要执行的操作,您可能还需要重置流的位置。我怀疑您会想要:
这与您的代码相同,但不会
Dispose()
流(因为它不再调用stream.Close()
),并将其重置到起始位置,如果您想读回对象/数据,这通常是必需的。You're calling
stream.Close()
, which is exactly the same as callingDispose()
on the stream.Just remove that line of code, and you should be fine. Basically, you need to leave the
MemoryStream
open when it's returned.On a different note, depending on what you're going to do, you may also want to reset the stream's position. I suspect you'll want:
This works the same as your code, but does not
Dispose()
the stream (since it's no longer callingstream.Close()
), and also resets it to the start position, which is often required if you want to read the object/data back out.在处理完流之前,不要调用stream.Close(或IDisposable.Dispose())。
您可能需要将流位置重新设置为开始
stream.Position = 0;
确保完成后处理该流。 using 语句是您的朋友。
Don't call stream.Close (or IDisposable.Dispose()) until you're done with the stream.
You probably need to set the stream position back to start
stream.Position = 0;
Make sure that you do dispose of the stream when you're done. The using statement is your friend here.
这是因为您
stream.Close();
对象。It's because you
stream.Close();
the object.您收到异常是因为您调用
Close()
。来自 MSDN:Stream 类您应该能够简单地删除
stream.Close();
。You are getting the exception because you call
Close()
. From MSDN: Stream ClassYou should be able to simply remove
stream.Close();
.