简体   繁体   English

在C#中将流转换为FileStream

[英]Convert a Stream to a FileStream in C#

What is the best method to convert a Stream to a FileStream using C#. 使用C#将Stream转换为FileStream的最佳方法是什么?

The function I am working on has a Stream passed to it containing uploaded data, and I need to be able to perform stream.Read(), stream.Seek() methods which are methods of the FileStream type. 我正在处理的函数有一个传递给它的Stream包含上传的数据,我需要能够执行stream.Read(),stream.Seek()方法,这些方法是FileStream类型的方法。

A simple cast does not work, so I'm asking here for help. 一个简单的演员阵容不起作用,所以我在这里寻求帮助。

Read and Seek are methods on the Stream type, not just FileStream . Read and SeekStream类型的方法,而不仅仅是FileStream It's just that not every stream supports them. 只是不是每个流都支持它们。 (Personally I prefer using the Position property over calling Seek , but they boil down to the same thing.) (我个人更喜欢使用Position属性而不是调用Seek ,但它们归结为同样的东西。)

If you would prefer having the data in memory over dumping it to a file, why not just read it all into a MemoryStream ? 如果您希望将内存中的数据转储到文件中,为什么不将它全部读入MemoryStream呢? That supports seeking. 这支持寻求。 For example: 例如:

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;
}

Use: 使用:

using (Stream input = ...)
{
    using (Stream memory = CopyToMemory(input))
    {
        // Seek around in memory to your heart's content
    }
}

This is similar to using the Stream.CopyTo method introduced in .NET 4. 这类似于使用.NET 4中引入的Stream.CopyTo方法。

If you actually want to write to the file system, you could do something similar that first writes to the file then rewinds the stream... but then you'll need to take care of deleting it afterwards, to avoid littering your disk with files. 如果你真的想要写入文件系统,你可以做一些类似的事情,首先写入文件然后倒回流...但是之后你需要注意删除它,以避免乱丢你的磁盘文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM