您的位置:首页 > 产品设计 > UI/UE

WebRequest 方式 文件下载

2012-11-21 20:49 330 查看
使用 WebRequest 直接下载会阻塞UI线程,要么使用多线程,要么使用异步方式

1)首先创建一个连接请求

string fullURL=@"http://neirong.funshion.com/software/download.php?id=6930&f=FunshionInstall2.6.6.43Beta.exe";
WebRequest webReq = WebRequest.Create(fullURL);

try
{
WebResponse webRes = webReq.GetResponse();
long fileLength = webRes.ContentLength;
Stream srm = webRes.GetResponseStream();
StreamReader srmReader = new StreamReader(srm);
byte[] bufferbyte = new byte[fileLength];
int MaxPro = (int)bufferbyte.Length;
progressBar1.Dispatcher.Invoke(new Action(()=>{
progressBar1.Maximum = MaxPro;
}));

int  Currentvalue = 0;
while (fileLength > 0)
{
int downByte = srm.Read(bufferbyte, Currentvalue, MaxPro);
if (downByte == 0) { break; };
Currentvalue += downByte;

progressBar1.Dispatcher.Invoke(new Action(() =>
{
progressBar1.Value = Currentvalue;
}));

MaxPro -= downByte;

float part = (float)Currentvalue / 1024;
float total = (float)bufferbyte.Length / 1024;
int percent = Convert.ToInt32((part / total) * 100);

}
string tempPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "测试下载");
CreateDirtory(tempPath);
FileNameInfo = System.IO.Path.Combine(tempPath, FileNameInfo);
FileStream fs = new FileStream(FileNameInfo, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bufferbyte, 0, bufferbyte.Length);
srm.Close();
srmReader.Close();
fs.Close();
}
catch
{
Console.WriteLine("下载文件异常");
}
}


下面是详细的下载

View Code

<Window x:Class="WpfApplication1.HttpdownLoadxaml"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="HttpdownLoadxaml" Height="300" Width="300">
<Grid>

<ProgressBar Height="10" Minimum="0"  HorizontalAlignment="Left" Margin="12,52,0,0" Name="progressBar1" VerticalAlignment="Top" Width="243" />
<Button Content="开始下载" Height="23" HorizontalAlignment="Left" Margin="41,207,0,0" Name="btnStart" VerticalAlignment="Top" Width="75" Click="btnStart_Click" />

<Button Content="暂停" Height="23" HorizontalAlignment="Right" Margin="0,207,31,0" Name="btnStop" VerticalAlignment="Top" Width="75" Click="btnStop_Click" />
</Grid>
</Window>


这个是使用一个 System.Threading.ThreadPool.QueueUserWorkItem(Down, new object()); } 进行下载,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: