在 C# 中将流转换为 FileStream

时间:2023-03-09
本文介绍了在 C# 中将流转换为 FileStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在处理的函数有一个 Stream 传递给它,其中包含上传的数据,我需要能够执行 stream.Read()、stream.Seek() 方法,这些方法是 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.

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

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

推荐答案

ReadSeekStream 类型上的方法,而不仅仅是文件流.只是不是每个流都支持它们.(我个人更喜欢使用 Position 属性而不是调用 Seek,但它们归结为同一件事.)

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.)

如果您更喜欢将数据保存在内存中而不是将其转储到文件中,为什么不将其全部读入MemoryStream?那支持寻求.例如:

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

使用:

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

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

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.

这篇关于在 C# 中将流转换为 FileStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何将整个流加载到 MemoryStream 中? 下一篇:如果使用“using"语句,是否需要在流或写入器

相关文章

最新文章