C#Read StreamReader网页Uri Relative

时间:2011-07-12 09:46:29

标签: c# windows-phone-7 uri relative-path streamreader

我下载阅读此网页的内容我正在使用此代码 这是一个Windows手机应用程序

string html = new StreamReader(Application.GetResourceStream(new Uri("http://www.knbsb.nl/nw/index.php?option=com_content&view=category&layout=blog&id=382&Itemid=150&lang=nl&LevelID=120&CompID=1580", UriKind.Relative)).Stream).ReadToEnd();

我知道UriKind设置为Relative,但必须是其他脚本。

所以基本上我必须从绝对的Uri到相对Urikind的网页。 但我不知道该怎么做!

3 个答案:

答案 0 :(得分:2)

您需要异步发出请求 你可以使用这样的东西作为帮手:

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();
                        }
                    }
                }

                callback(responseString, null);
            }
            catch (Exception ex)
            {
                callback(null, ex);
            }
        };

        req.BeginGetResponse(getTheResponse, req);
    }
    catch (Exception ex)
    {
        callback(null, ex);
    }
}

然后你可以这样打电话:

private void Button_Click(object sender, RoutedEventArgs e)
{
    RequestAsync(
        new Uri("http://www.knbsb.nl/nw/index.php?option=com_content&view=category&layout=blog&id=382&Itemid=150&lang=nl&LevelID=120&CompID=1580"),
        (html, exc) =>
            {
                if (exc == null)
                {
                    Dispatcher.BeginInvoke(() => MessageBox.Show(html));
                }
                else
                {
                    // handle exception appropriately
                }
            });
}

答案 1 :(得分:0)

您可以使用WebClient来执行此操作。

  using (var client = new WebClient())
        {
            string result = client.DownloadString("http://www.youtsite.com");
//do whatever you want with the string. 

    }

答案 2 :(得分:0)

Application.GetResourceStream用于从应用程序包中读取资源,而不是从Web请求资源。

请改用HttpWebRequestWebClient类。

示例:

string html;
using (WebClient client = new WebClient()) {
  html = client.DownloadString("http://www.knbsb.nl/nw/index.php?option=com_content&view=category&layout=blog&id=382&Itemid=150&lang=nl&LevelID=120&CompID=1580");
}