加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将流转换为C#中的FileStream

发布时间:2020-12-15 04:20:27 所属栏目:百科 来源:网络整理
导读:使用C#将Stream转换为FileStream的最佳方法是什么? 我正在处理的功能有一个Stream传递给它包含上传的数据,我需要能够执行Stream.Read(),stream.Seek()方法,这是FileStream类型的方法. 一个简单的演员不行,所以我在这里求助. 解决方法 Read和Seek是Stream类
使用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方法类似.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读