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

5 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

Igor Monteiro said...

your solution smell like a shit..

Leslie Lim said...

I read your blog.I thought it was great.. Hope you have a great day. God bless.

Rica
www.imarksweb.org

sarah lee said...

I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


edupdf.org

Post a Comment