在C#中将流转换为FileStream

使用C#将Stream转换为FileStream的最佳方法是什么?

我正在处理的函数有一个传递给它的Stream包含上传的数据,我需要能够执行stream.Read(),stream.Seek()方法,这些方法是FileStream类型的方法。

一个简单的演员阵容不起作用,所以我在这里寻求帮助。

Read and SeekStream类型的方法,而不仅仅是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 } } 

这类似于使用.NET 4中引入的Stream.CopyTo方法。

如果你真的想要写入文件系统,你可以做类似的事情,首先写入文件然后重新流动…但是之后你需要注意删除它,以避免乱丢你的磁盘与文件。