C#中使用WebClient对象下载文件

来源:互联网 发布:没有更新到数据库 编辑:程序博客网 时间:2024/05/01 01:29

/// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="sourceFileUrl"></param>
        /// <param name="savePath"></param>
        private void ActionDownLoadFile(string sourceFileUrlAddress, string savePath)
        {
            string fileName = "";
            byte[] mbyte = new byte[51200];
            int allmybyte = mbyte.Length;
            long nowFinish = 0;
            int m = 0;
            //写入到BYTE数组中,起缓冲作用
            FileStream fstr = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);
            int lastSplitChar = sourceFileUrlAddress.LastIndexOf("/");
            WebClient client = new WebClient();
            Stream str = null;
            long totalbytes = 0;

            try
            {
                this.ShowActionText("链接下载文件...");
                fileName = sourceFileUrlAddress.Substring(lastSplitChar + 1);             //获得文件名
                client.DownloadFile(sourceFileUrlAddress, fileName);
                str = client.OpenRead(sourceFileUrlAddress);
                totalbytes = Convert.ToInt64(client.ResponseHeaders["Content-Length"]);
                while (nowFinish < totalbytes || m > 0)
                {
                    m = str.Read(mbyte, 0, allmybyte);
                    fstr.Write(mbyte, 0, m);
                    this.ShowActionText("正在接收数据...    " + string.Format("{0:f}%,完成:{1},总共:{2} 字节", (double)(nowFinish * 100) / totalbytes, nowFinish, totalbytes));
                    if (m == 0)
                        break;
                    nowFinish += m;
                }
                str.Close();
                fstr.Close();
                this.ShowActionText("下载完毕!");
             }
             catch (WebException ex)
             {
                 throw new Exception(ex.Message);
             }
        }


调用如下:   ActionDownLoadFile("http://www.abc123.com/logo.jpg","E:/logo.jpg");

原创粉丝点击