转换流在C#中的FileStream [英] Convert a Stream to a FileStream in C#

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

问题描述

什么是用C#一个流转换为一个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.

感谢。

推荐答案

寻找是在 Stream方法类型,而不是刚的FileStream 。只是,不是每个流支持他们。 (我个人更喜欢使用 位置在调用寻找,但它们归结为同样的事情。)

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆