在C#中将流转换为FileStream

Gre*_*reg 13 c# stream filestream

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

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

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

Jon*_*eet 20

Read并且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;
}
Run Code Online (Sandbox Code Playgroud)

使用:

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

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

如果你确实要写入到文件系统,你可以做类似的,首先写入文件,然后倒带流的东西......但那么你就需要照顾删除它之后,以避免乱抛垃圾文件的磁盘.