将流转换为C#中的FileStream

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

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

一个简单的演员不行,所以我在这里求助.

解决方法

Read和Seek是Stream类型的方法,而不仅仅是FileStream.只是不是每个流都支持它们. (个人而言,我更喜欢使用 Position property调用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,buffer.Length)) > 0)
    {
        ret.Write(buffer,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
    }
}

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

如果你真的想写入文件系统,你可以做一些类似的操作,首先写入文件,然后倒带流…但是之后你需要保留删除它,以避免用文件乱丢磁盘.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...