如何在Windows 8应用程序中获取html源代码

时间:2012-11-08 09:58:36

标签: c# windows-8

在Windows 8中,我尝试从URL获取html源代码:

private void loadingDatafromWeb(string URL)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
    request.BeginGetResponse(new AsyncCallback(ReadCallbackLoadingData),request);
}

private void ReadCallbackLoadingData(IAsyncResult asynchronousResult)
{
    string myPageSource;
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
    HttpWebResponse response =   (HttpWebResponse)request.EndGetResponse(asynchronousResult);
    using (StreamReader myWebSource = new StreamReader(response.GetResponseStream()))
    {
        myPageSource = myWebSource.ReadToEnd();
    }

我想在函数loadingDatafromWeb中获取字符串myPageSource,但我不能这样做。请告诉我怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用新的.Net 4.5功能,并使用await关键字呼叫:

private void loadingDatafromWeb(string URL)
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
    string html = await ReadData(new Uri(request));
}

你的助手方法是:

private async Task<string> ReadData(Uri uri)
{
     string result;

     // Get your response synchronously (do not forget to enscope WebResponse
     // and other Streams inside 'usings').

     return result;
}