什么是使用C#将流(Stream)转换为FileStream的最佳方法?
我正在处理一个包含上传数据的Stream,需要执行FileStream类型的stream.Read()和stream.Seek()方法。简单的强制转换并不起作用,因此我在这里请求帮助。
我正在处理一个包含上传数据的Stream,需要执行FileStream类型的stream.Read()和stream.Seek()方法。简单的强制转换并不起作用,因此我在这里请求帮助。
Read
和Seek
是Stream
类型的方法,不仅适用于FileStream
。只是并非所有流都支持它们。(个人更喜欢使用Position
属性而不是调用Seek
,但它们归根结底是相同的。)
如果您希望将数据保存在内存中而不是转储到文件中,为什么不将其全部读入MemoryStream
中呢?它支持寻址。例如:
public static MemoryStream CopyToMemory(Stream input)
{
// It won't matter if we throw an exception during this method;
// we don't *really* need to dispose of the MemoryStream, and the
// caller should dispose of the input stream
MemoryStream ret = new MemoryStream();
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
ret.Write(buffer, 0, bytesRead);
}
// Rewind ready for reading (typical scenario)
ret.Position = 0;
return ret;
}
使用:
using (Stream input = ...)
{
using (Stream memory = CopyToMemory(input))
{
// Seek around in memory to your heart's content
}
}
FileStream
,这个示例会如何改变? - Josh Sharkey