Reading webpage contents as a string in Windows Phone 7.
Hello all….
I am new to Windows Phone 7. So I am starting by posting a simple tutorial Here.
In this post I will try to read a webpage contents as a string and show it in a MessageBox.
Here is the complete code.
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using System.IO; namespace PhoneApp1 { public partial class MainPage : PhoneApplicationPage { public MainPage() { InitializeComponent(); RequestAsync( new Uri("http://google.com"), (html, exc) => { if (exc == null) { Dispatcher.BeginInvoke(() => MessageBox.Show(html)); } else { // handle exception appropriately } }); } public static void RequestAsync(Uri url, Action<string, Exception> callback) { if (callback == null) { throw new ArgumentNullException("callback"); } try { var req = WebRequest.CreateHttp(url); AsyncCallback getTheResponse = ar => { try { string responseString; var request = (HttpWebRequest)ar.AsyncState; using (var resp = (HttpWebResponse)request.EndGetResponse(ar)) { using (var streamResponse = resp.GetResponseStream()) { using (var streamRead = new StreamReader(streamResponse)) { responseString = streamRead.ReadToEnd(); Console.WriteLine(responseString); } } } callback(responseString, null); } catch (Exception ex) { callback(null, ex); } }; req.BeginGetResponse(getTheResponse, req); } catch (Exception ex) { callback(null, ex); } } } }
Thank you verymuch. This post is very useful. It help me alot. Many thanks…. 🙂