views:

4363

answers:

2

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? -g

A: 

have you tried resetting the stream position? if this does not work you can copy the stream to a MemoryStream and there you can reset the position (i.e. to 0) as often as you want.

Joachim Kerschbaumer
+15  A: 

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

Stream responseStream = CopyStream(resp.GetResponseStream());
// Do something with the stream
responseStream.Seek(0, SeekOrigin.Begin);
// Do something with the stream again


    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);
  return ms;
 }
Iain
One tiny suggestion here - I often see calls to Seek where the Position property would be simpler and more readable, e.g.ms.Position = 0;Just a thought for future code.
Jon Skeet
Another comment - the above doesn't end up closing the incoming stream, ever. It might be worth creating a "CopyAndClose" method which *does* close the stream, just so you could keep the simple calling syntax.
Jon Skeet
Wow, coming close to my heroes.. I'm currently reading your book, Mr. Skeet :-) What you suggested about closing (and telling with the method name) is exactly what I thought about the above code.
VVS
Worked great! Thanks guys... -Greg
greg7gkb