Silverlight中WebClient下载资源

首先新建一个Silverlight应用程序带Web的,在Web程序中放入一个txt文件,名为TextFile1.txt。内容Silverlight is very good!

然后在silverlight项目中添加一个silverlight user control名为WebClientDownResource.xaml

xaml的内容为:

<Grid x:Name="LayoutRoot" Background="White">
        
<Grid.ColumnDefinitions>
            
<ColumnDefinition>
            
</ColumnDefinition>
        
</Grid.ColumnDefinitions>
        
<Grid.RowDefinitions>
            
<RowDefinition Height="Auto">
            
</RowDefinition>
            
<RowDefinition Height="auto">
            
</RowDefinition>
            
<RowDefinition Height="auto" >
            
</RowDefinition>
        
</Grid.RowDefinitions>
        
        
<Button Grid.Row="1" Grid.Column="0" Content="DownText" Height="23" HorizontalAlignment="Left"  Name="Down" VerticalAlignment="Top" Width="75" Margin="12,0,0,0" Click="Down_Click" />
        
<TextBlock  Grid.Row="0" Grid.Column="0" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" Width="350" />
        
<ProgressBar Grid.Row="2" Grid.Column="0" Height="10" HorizontalAlignment="Left" Margin="10,10,0,0" Name="progressBar1" VerticalAlignment="Top" Width="100" />

    </Grid> 

后台的代码:

private void Down_Click(object sender, RoutedEventArgs e)

        {
            string uri = Application.Current.Host.Source.AbsoluteUri;
            
int index = uri.IndexOf("/ClientBin");
            uri 
= uri.Substring(0, index) + "/TextFile1.txt";

            WebClient webClient 
= new WebClient();
            webClient.OpenReadCompleted 
+= new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
            webClient.DownloadProgressChanged 
+= new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            webClient.OpenReadAsync(
new Uri(uri));
        }

        
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            
this.progressBar1.Value = e.ProgressPercentage;
        }
        
private void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            
if (e.Error != null)
            {
                
// (Add code to display error or degrade gracefully.)
            }
            
else
            {
                Stream stream 
= e.Result;
               StreamReader reader
=new StreamReader(stream);
                
this.textBlock1.Text=reader.ReadToEnd();
                reader.Close();
            }
        }
 
具体的关于webclient的内容可以参考《pro silverlight 4 in c#》中的第6章内容。
posted @ 2011-04-24 17:16  chenping2008  阅读(1573)  评论(2编辑  收藏  举报