Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows 8 C# - retrieve a webpage source as string

Tags:

html

c#

windows-8

there's a tutorial that actually works for Windows 8 platform with XAML and C#: http://www.tech-recipes.com/rx/1954/get_web_page_contents_in_code_with_csharp/

Here's how:

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sr.Close();
myResponse.Close();

However in Windows 8, the last 2 lines which are code to close the connection (I assume), detected error. It works fine without closing the connection, though, but what are the odds? Why do we have to close the connection? What could go wrong if I don't? What do "closing connection" even mean?

like image 816
Hendra Anggrian Avatar asked Oct 22 '22 07:10

Hendra Anggrian


1 Answers

If you are developing for Windows 8, you should consider using asynchronous methods to provide for a better user experience and it is the recommend new standard. Your code would then look like:

public async Task<string> MakeWebRequest(string url)
{
    HttpClient http = new System.Net.Http.HttpClient();
    HttpResponseMessage response = await http.GetAsync(url);
    return await response.Content.ReadAsStringAsync();
}
like image 72
Erik Schierboom Avatar answered Nov 09 '22 23:11

Erik Schierboom