我正在尝试将流写入 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/