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?
Teeing a stream Sometimes you might want to read a stream twice, simultaneously. This is achieved via the ReadableStream.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With