shakarchi
shakarchi

Reputation: 43

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.

Upvotes: 3

Views: 4020

Answers (2)

Tom Tregenna
Tom Tregenna

Reputation: 1311

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.

Upvotes: 4

andy
andy

Reputation: 6079

May be "req.GetResponse();" taking more time..... When your putting the break point its getting time to complete the task.

You need to check

resp.StatusDescription

before

System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());

Upvotes: 0

Related Questions