WP7->网络->读取网页源码

问题:如何读取一个网页的源码

  我的理解:其实很简单,只需要用“WebClient”类即可

 

示例:

读取百度首页源码,然后放到messgaebox中show出来

 

前置条件:

1)  C#基础

2)  XAML基础

 

实现:

目录:

1)  创建一个基本应用

2)  添加一个按钮

3)  添加事件代码

4)  测试运行

 

1 创建一个基本应用

1)  创建一个基本的Windows Phone应用程序,OS版本7.0

2)  清除多余的界面元素(留下一个基本的Grid控件)

1 <Grid x:Name="LayoutRoot" Background="Transparent">
2 
3 </Grid>

2 添加一个按钮

1     <Grid x:Name="LayoutRoot" Background="Transparent">
2         <Button Content="Do" Height="72" HorizontalAlignment="Left" Margin="157,169,0,0" Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
3     </Grid>

3 添加事件代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Windows;
 6 using System.Windows.Controls;
 7 using System.Windows.Documents;
 8 using System.Windows.Input;
 9 using System.Windows.Media;
10 using System.Windows.Media.Animation;
11 using System.Windows.Shapes;
12 using Microsoft.Phone.Controls;
13 using System.IO;
14 
15 namespace PhoneApp1
16 {
17     public partial class MainPage : PhoneApplicationPage
18     {
19         // 构造函数
20         public MainPage()
21         {
22             InitializeComponent();
23             
24         }
25 
26         private void button1_Click(object sender, RoutedEventArgs e)
27         {
28             WebClient webClient = new WebClient();
29             webClient.OpenReadAsync(new Uri("http://www.baidu.com"));
30             webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
31         }
32 
33         void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
34         {
35             using (StreamReader reader = new StreamReader(e.Result))
36             {
37                 MessageBox.Show(reader.ReadToEnd());
38             }
39         }
40     }
41 }

4 测试运行

 

 说明:

  1)  使用OpenReadAsync方法设置需要读取的页面,其本意是“开启指定资源的数据流”

  2)  设置OpenReadCompleted事件,并在事件中读取结果

 

posted @ 2012-11-02 16:43  布兰姥爷  阅读(351)  评论(0编辑  收藏  举报