silverlight3 MainPage.xaml如下:
<UserControl x:Class="SilverlightApplication2.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480" >
<Grid x:Name="LayoutRoot">
<Button Content="下载文件" Height=" 20" Width=" 100" Click="Button_Click" ></Button>
<ProgressBar x:Name="progressbar1" Width="300" Height="10" Margin="0,70,20,20"></ProgressBar>
<TextBlock x:Name="txtinfo" Text=" ss" Margin="0,150,20,20" Width=" 300" Height=" 50"/>
</Grid>
</UserControl>
MainPage.xaml.cs如下:
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 System.IO;
namespace SilverlightApplication2
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//_file 要下载的文件路径
string _file = "http://localhost:1490/aa.rar"; //这里改成你网站里的文件路径
SaveFileDialog sf = new SaveFileDialog();
if (sf.ShowDialog() != true) return;
Stream clientStream = sf.OpenFile();
Uri _uri = new Uri(_file, UriKind.Absolute);
WebClient client = new WebClient();
if (client.IsBusy)
{
client.CancelAsync();
}
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(_uri, clientStream);
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
txtinfo.Text += e.Error.Message;
return;
}
if (e.Cancelled != true)
{
Stream clientStream = e.UserState as Stream;
Stream serverStream = (Stream)e.Result;
byte[] buffer = new byte[serverStream.Length];
serverStream.Read(buffer, 0, buffer.Length);
clientStream.Write(buffer, 0,buffer.Length);
clientStream.Close();
serverStream.Close();
}
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressbar1.Value =(double) e.ProgressPercentage;
txtinfo.Text = string.Format("完成的百分比:{0}\r\n已下载的字节数:{1}\r\n数要载的总字节数:{2}\r\n",
e.ProgressPercentage.ToString(),
e.BytesReceived.ToString(),
e.TotalBytesToReceive.ToString());
}
}
}
![](https://pic002.cnblogs.com/images/2011/129582/2011030215102747.jpg)