c# - 像写入文件一样写入流,但实际上写入对象

标签 c# stream memorystream

我正在尝试将流写入 ram 而不是文件。我试过这样做:

Stream stream = new MemoryStream();
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
return stream;

但是,当我在据称写入流后查看流时,它说“Length = 'stream.Length' throw an exception of type 'System.ObjectDisposedException'”

最佳答案

在获取数据之前不要关闭流,并且不返回流而是返回流的内容:

using (Stream stream = new MemoryStream()) {
  BinaryFormatter bFormatter = new BinaryFormatter();
  bFormatter.Serialize(stream, objectToSerialize);
  return stream.ToArray();
}

关于c# - 像写入文件一样写入流,但实际上写入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290109/

相关文章:

c# - 如何在 C# 插入查询中使用循环

c# - 将 IntPtr 指向的内存内容发送到 C# 上的 MemoryStream 变量

Android MediaPlayer Streaming setDataSource FileNotFoundException : No content provider

java - 如何使用Java streams和reduce()获取Map的key和value的计算总和?

node.js - 如何在 node.js 中编写转换流

c# - Web Api 2 - 如何在不保存到磁盘的情况下从 HTTPGET 返回图像(来自 Azure 存储的 MemoryStream)?

c# - 调用 Stream.Write 和使用 StreamWriter 有什么区别?

c# - 如何推迟 WPF 文本框中的更新

c# - 禁用 Entity Framework 代理创建

c# - 在 Visual Studio 中 Hook 构建过程