Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read an Http response stream twice in C#?

Tags:

c#

stream

I am trying to read an Http response stream twice via the following:

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); stream = response.GetResponseStream(); RssReader reader = new RssReader(stream); do {   element = reader.Read();   if (element is RssChannel)   {     feed.Channels.Add((RssChannel)element);   } } while (element != null);  StreamReader sr = new StreamReader(stream); feed._FeedRawData = sr.ReadToEnd(); 

However when the StreamReader code executes there is no data returned because the stream has now reached the end. I tried to reset the stream via stream.Position = 0 but this throws an exception (I think because the stream can't have its position changed manually).

Basically, I would like to parse the stream for XML and have access to the raw data (in string format).

Any ideas?

like image 387
greg7gkb Avatar asked Sep 29 '08 08:09

greg7gkb


People also ask

Can you read stream twice?

Teeing a stream Sometimes you might want to read a stream twice, simultaneously. This is achieved via the ReadableStream.

Can you read a stream twice C#?

You can not read the input stream twice, even if you will try to set the position, it will give error. What you have to do is to create a new stream and use it as many times as you want: MemoryStream newStream = new MemoryStream(); // CopyTo method used to copy the input stream into newStream variable.

How do I write from one stream to another?

CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size. Both streams positions are advanced by the number of bytes copied.


1 Answers

Copy it into a new MemoryStream first. Then you can re-read the MemoryStream as many times as you like:

Stream responseStream = CopyAndClose(resp.GetResponseStream()); // Do something with the stream responseStream.Position = 0; // Do something with the stream again   private static Stream CopyAndClose(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.Position = 0;     inputStream.Close();     return ms; } 
like image 189
Iain Avatar answered Sep 23 '22 17:09

Iain