如何读取流,并重置其位置设置为0,即使stream.CanSeek ==假 [英] How to read a Stream and reset its position to zero even if stream.CanSeek == false

查看:1625
本文介绍了如何读取流,并重置其位置设置为0,即使stream.CanSeek ==假的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了流并重置其位置设置为0怎么办即使 stream.CanSeek ==虚假?我需要一些变通。

How do I read a Stream and reset its position to zero even if stream.CanSeek == false? I need some work around.

推荐答案

如果您的方案允许您以取代原来的流,那么你可以检查它是否支持寻求并且,如果没有,阅读其内容,并将其包装成一个新的的MemoryStream ,然后你可以使用的后续操作。

If your scenario permits you to replace your original stream, then you could check whether it supports seeking and, if not, read its content and wrap them into a new MemoryStream, which you could then use for subsequent operations.

static string PeekStream(ref Stream stream)
{
    string content;
    var reader = new StreamReader(stream);
    content = reader.ReadToEnd();

    if (stream.CanSeek)
    {
        stream.Seek(0, SeekOrigin.Begin);
    }
    else
    {
        stream.Dispose();
        stream = new MemoryStream(Encoding.UTF8.GetBytes(content));
    }

    return content;
}



以上是相当低效的,因为它必须为两倍大小的分配内存您的内容。我的建议是,以适应你的代码你在哪里,以便访问流(后读过的所有内容)的部分,使他们访问您的内容的存储副本,而不是。例如:

The above is rather inefficient, since it must allocate memory for twice the size of your content. My recommendation would be to adapt the parts of your code where you’re accessing the stream (after having read all its content) in order to make them access the stored copy of your content instead. For example:

string content;
using (var reader = new StreamReader(stream))
    content = reader.ReadToEnd();

// Process content here.

string line;
using (var reader = new StringReader(content))
    while ((line = reader.ReadLine()) != null)
        Console.WriteLine(line);



由于 StringReader 刚刚从读您的内容字符串,你就不会浪费内存创建数据的冗余副本。

Since the StringReader just reads from your content string, you would not waste memory creating redundant copies of your data.

这篇关于如何读取流,并重置其位置设置为0,即使stream.CanSeek ==假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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