Convert a Stream to a FileStream in C#

天大地大妈咪最大 提交于 2019-11-27 14:49:59

问题


What is the best method to convert a Stream to a FileStream using C#.

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.

A simple cast does not work, so I'm asking here for help.


回答1:


Read and Seek are methods on the Stream type, not just 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.)

If you would prefer having the data in memory over dumping it to a file, why not just read it all into a 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.

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.



来源:https://stackoverflow.com/questions/3769067/convert-a-stream-to-a-filestream-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!