Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 973
Faisal Avatar asked Jan 22 '12 13:01

Faisal


2 Answers

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.

like image 93
Douglas Avatar answered Nov 10 '22 00:11

Douglas


Use another Stream implementation that supports seeking. If Stream.CanSeek returns false, then that implementation is asserting that it does not support seeking.

The MemoryStream object does support seeking. You can copy an arbitrary stream to a MemoryStream using something like this, and the resulting stream will support seeking, e.g., you can reset the position to 0 and read from it repeatedly.

MemoryStream CopyStreamToMemory(Stream inputStream)
{
    MemoryStream ret = new MemoryStream();
    const int BUFFER_SIZE = 1024;
    byte[] buf = new byte[BUFFER_SIZE];

    int bytesread = 0;
    while ((bytesread = inputStream.Read(buf, 0, BUFFER_SIZE)) > 0)
        ret.Write(buf, 0, bytesread);

    ret.Position = 0;
    return ret;
}

Of course, if your stream reads data that does not change, you can simply dispose the old stream, and create a new stream that reads the same data.

like image 32
drf Avatar answered Nov 10 '22 00:11

drf