如何从 .NET 中的流中获取 MemoryStream? [英] How to get a MemoryStream from a Stream in .NET?

查看:40
本文介绍了如何从 .NET 中的流中获取 MemoryStream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下构造函数方法可以从文件路径打开 MemoryStream:

I have the following constructor method which opens a MemoryStream from a file path:

MemoryStream _ms;

public MyClass(string filePath)
{
    byte[] docBytes = File.ReadAllBytes(filePath);
    _ms = new MemoryStream();
    _ms.Write(docBytes, 0, docBytes.Length);
}

我需要将其更改为接受 Stream 而不是文件路径.从 Stream 对象获取 MemoryStream 的最简单/最有效的方法是什么?

I need to change this to accept a Stream instead of a file path. Whats the easiest/most efficient way to get a MemoryStream from the Stream object?

推荐答案

如果您要修改类以接受 Stream 而不是文件名,请不要费心转换为 MemoryStream.让底层 Stream 处理操作:

If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:

public class MyClass
{ 
    Stream _s;

    public MyClass(Stream s) { _s = s; }
}

但是如果你真的需要一个 MemoryStream 来进行内部操作,你就必须将源 Stream 中的数据复制到 MemoryStream 中:

But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:

public MyClass(Stream stream)
{
    _ms = new MemoryStream();
    CopyStream(stream, _ms);
}

// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[16*1024];
    int read;
    while((read = input.Read (buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

这篇关于如何从 .NET 中的流中获取 MemoryStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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