I'm new to C# and trying to get my head around why the code below isn't working. I've tried to make a custom class HtmlRequest that isn't static so can be instantiated as many times as required using HtmlRequest someVar = new HtmlRequest();
return sb is holding the value but it's not being returned to hmtmlString on the line htmlString = htmlReq.getHtml(uri).
I've tried putting Get{code ...return sb;} after public class HtmlRequest but can't get the correct syntax
public partial class MainWindow : DXWindow
{
private void GetLinks()
{
HtmlRequest htmlReq = new HtmlRequest();
Uri uri = new Uri("http://stackoverflow.com/");
StringBuilder htmlString = new StringBuilder();
htmlString = htmlReq.getHtml(uri); //nothing returned on htmlString
}
}
public class HtmlRequest
{
public StringBuilder getHtml(Uri uri)
{
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
Do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
return sb;
}
}
If I put a breakpoint on return sb; then the variable is correct but is not returning it.
It's probably something really obvious, can someone explain why it's not working and how to fix it?
Thank you
string pause;and checked. If I actually use the variable then it has a value. That's a bit annoying! Is there any reason for this behaviour? If you add that as an answer I'll accept.