C# 下载网络文件

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Management;

        

GetDownFiles(sUrl, ( "C:\DownFiles.Tmp"), LabDownMess, pBar2);
 

 

        //下载文件   
        //=================================================================================
        public static Boolean GetDownFiles(string url, string LocalPath,Label LabDownMess,ProgressBar pBar2)
        {
            try
            {
                //先删除临时下载文件
                if (File.Exists(LocalPath))
                {
                    File.Delete(LocalPath);
                }


                //下载
                Uri u = new Uri(url);
                HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
                mRequest.Method = "GET";
                mRequest.ContentType = "application/x-www-form-urlencoded";

                HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();

                Stream sIn = wr.GetResponseStream();

                long length = wr.ContentLength;

                pBar2.Minimum = 0;
                pBar2.Maximum = (Int32)length;
                pBar2.Value = 0;

               

                byte[] mbyte = new byte[100000000];
                int startmbyte = 0;
                while (length > 0)
                {
                    int m = sIn.Read(mbyte, startmbyte, (int)length);
                    if (m == 0)
                        break;

                    startmbyte += m;
                    length -= m;
                    pBar2.Value = (Int32)startmbyte;
                    LabDownMess.Text = "当前下载文件大小:" + (length + startmbyte).ToString() + "字节   当前下载大小:" + startmbyte.ToString() + "字节";
                    Application.DoEvents();
                }
                FileStream fstr = new FileStream(LocalPath, FileMode.OpenOrCreate, FileAccess.Write);
                fstr.Write(mbyte, 0, startmbyte);
                sIn.Close();
                fstr.Close();
                wr.Close();

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }

        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值