Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader returns empty string

I have the following code:

  System.Net.WebRequest req = System.Net.WebRequest.Create(url);
  req.Credentials = new NetworkCredential("admin", "password");
  System.Net.WebResponse resp = req.GetResponse();
  System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
  var result = sr.ReadToEnd().Trim();

When I run the code the result is just an empty string. However when I step through the code the result is a string with data in it, as I was expecting, when I put a breakpoint on this line:

System.Net.WebResponse resp = req.GetResponse();

So I think the problem lies with this or the subsequent line. Not sure how to proceed, help would be appreciated.

like image 968
shakarchi Avatar asked Aug 26 '26 06:08

shakarchi


1 Answers

I came across a similar issue whilst using CopyToAsync() on a WebResponse, it turned out that the Stream's pointer was ending up at the end of the Stream (it's pointer position was equal to it's length).

If this is the case, you can reset the pointer before reading the contents of the string with the following...

var responseStream = resp.GetResponseStream();

responseStream.Seek(0, SeekOrigin.Begin);

var sr = new StreamReader(responseStream);
var result = sr.ReadToEnd().Trim();

Although, since you're reading the stream directly, and not copying it into a new MemoryStream, this may not apply to your case.

like image 58
Tom Tregenna Avatar answered Aug 28 '26 02:08

Tom Tregenna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!