Pages

Friday, January 15, 2010

C# Reading from a closed Stream

Basicaly, when you read from a Stream, you must close it after you are done.  But what if at some point later you need to open it and read it again?  Even after trying to reopen it, it seems like the pointer is at the end and it just finishes :S

We copy the stream we want to read first, then read that copied stream.  I found this code on the net somewhere, can't remember now.  Very handy, stored here for later reference :)

*edit* updated by adding one line to the CopyStream method

...
//Copy the stream first so we can open it several times
Stream responseStream = CopyStream(attachment.ContentStream);

// convert stream to string
using (StreamReader reader = new StreamReader(responseStream))
{
    string text = reader.ReadToEnd();
    return text;
}
...

///
/// Copy the stream for reading and writing
///
///
///
private static Stream CopyStream(Stream inputStream)
{
    const int readSize = 256;
    byte[] buffer = new byte[readSize];
    MemoryStream ms = new MemoryStream();

    int count = inputStream.Read(buffer, 0, readSize);
    while (count > 0)
    {
        ms.Write(buffer, 0, count);
        count = inputStream.Read(buffer, 0, readSize);
    }
    ms.Seek(0, SeekOrigin.Begin);
    inputStream.Seek(0, SeekOrigin.Begin); 
    return ms;
}

2 comments:

Vivek said...

inputStream has CanRead set to false. so CopyStream throws exception during Read

-Vivek

Vivek said...

inputStream has CanRead set to false. so CopyStream throws exception during Read

-Vivek

Post a Comment