Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c# - How to read a Stream and reset its position to zero even if stream.CanSeek == false

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...