WebRequest 方式 文件下载

本文介绍了如何使用WebRequest进行文件下载,并通过多线程和异步方式避免阻塞UI线程。具体步骤包括创建连接请求、获取响应流、读取文件内容并写入本地文件,同时提供了详细的代码示例和下载界面实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 使用 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
using System;
using System.Windows;
using System.Net;
using System.IO;

namespace WpfApplication1
{
    /// <summary>
    /// HttpdownLoadxaml.xaml 的交互逻辑
    /// </summary>
    public partial class HttpdownLoadxaml : Window
    {
        public HttpdownLoadxaml()
        {
            InitializeComponent();
            progressBar1.DataContext = this;
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(Down, new object());
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {

        }


        private void Down(object obj)
        {
            LoadFile(null, @"http://neirong.funshion.com/software/download.php?id=6930&f=FunshionInstall2.6.6.43Beta.exe");
        
        }
       // http://neirong.funshion.com/software/download.php?id=6930&f=FunshionInstall2.6.6.43Beta.exe
        /// <summary>
        /// 下载文件信息s
        /// </summary>
        /// <param name="basepath"></param>
        /// <param name="filePath"></param>
        void LoadFile(string basepath, string filePath)
        {
            string FileNameInfo = Path.GetFileName(filePath);
            //string fullURL = string.Concat(basepath, filePath.Replace("\\", "/"));
            //if (fullURL.IndexOf("http") < 0) return;
            //// 测试
           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("下载文件异常");
            }
        }



        void CreateDirtory(string tempPath)
        {
            if (!Directory.Exists(tempPath))
                Directory.CreateDirectory(tempPath);
        }

       
             

    }
}

前台界面可以这样

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()); } 进行下载,

转载于:https://www.cnblogs.com/wzxflu/archive/2012/11/21/2781471.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值