NEWS

[C#] Tách file thành nhiều phần để download

[C#] Tách file thành nhiều phần để download
Đăng bởi: Thảo Meo - Lượt xem: 9345 09:09:19, 16/04/2018DEVEXPRESS   In bài viết

Bài viết hôm nay, mình sẽ hướng dẫn các bạn cách chia nhỏ file để download trong lập trình C#.

[C#] SPLIT FILE AND DOWNLOAD MULTI PART FILE

Hầu hết, các ứng dụng download hiện nay đều tích hợp sẵn chia nhỏ file để download. Thường các bạn sẽ thấy trong ứng dụng download Internet Download Manager.

Trong phần cài đặt bạn có thể chọn từ 1-32 phần, để download. 

Nếu các bạn download file dung lượng nhỏ thì không sao, nhưng giả sử nếu các bạn download file khoảng 5GB. Thì mình có thể chia nhỏ thành 5 phần, 1 phần 1GB để download.

download multi part file c#

Dưới đây là demo mình download file Teamviewer C#

download multipart file

Source code C#:

using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DownloadMultiPartFile
{
    public partial class Form1 : Form
    {
        string filename;
        int tastCount;

        public Form1()
        {
            InitializeComponent();
        }

        private void DownloadPart(WebResponse webResp, Stream respStream, byte[] buff,
           int offset, int remainingBytes, int totalBytes, ProgressBarControl bar)
        {
            respStream.BeginRead(buff, offset, remainingBytes, rcb =>
            {
                var readcount = ((Stream)rcb.AsyncState).EndRead(rcb);
                totalBytes += readcount;
                offset += readcount;
                remainingBytes -= readcount;
                bar.BeginInvoke(new Action(() =>
                {
                    bar.EditValue = totalBytes;
                    progressBarControl4.BeginInvoke(new Action(() =>
                    {
                        progressBarControl4.EditValue = (int)progressBarControl4.EditValue + readcount;
                    }));
                    if (remainingBytes > 0)
                    {
                        DownloadPart(webResp, respStream, buff, offset, remainingBytes, totalBytes, bar);
                    }
                    else
                    {
                        respStream.Flush();
                        respStream.Close();
                        respStream.Dispose();
                        webResp.Close();
                        webResp.Dispose();
                        lock (this)
                        {
                            tastCount--;
                            if (tastCount == 0)
                            {
                                FileStream fs = new FileStream(filename, FileMode.OpenOrCreate,
                                    FileAccess.Write, FileShare.None);
                                progressBarControl4.EditValue = 0;
                                progressBarControl4.Properties.Maximum = buff.Length;
                                writeByte2File(buff, fs, 0, buff.Length, 0);
                            }
                        }
                    }
                }));
            }, respStream);
        }

        private void writeByte2File(byte[] buff, FileStream fs, int offset, int remainingBytes, int totalBytes)
        {
            fs.BeginWrite(buff, offset, Math.Min(remainingBytes, 200000), wcb =>
            {
                //int readCount = ((FileStream)wcb.AsyncState).EndWrite(wcb);
                ((FileStream)wcb.AsyncState).EndWrite(wcb);
                int writeCount = 200000;
                offset += writeCount;
                remainingBytes -= writeCount;
                totalBytes += writeCount;
                progressBarControl4.BeginInvoke(new Action(() =>
                {
                    progressBarControl4.EditValue = totalBytes;
                    if (remainingBytes > 0)
                    {
                        writeByte2File(buff, fs, offset, remainingBytes, totalBytes);
                    }
                    else
                    {
                        fs.Flush();
                        fs.Close();
                        fs.Dispose();
                        MessageBox.Show("completed");
                    }
                }));
            }, fs);
        }

        private HttpWebRequest createRequest(string url)
        {
            HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(url);
            return rq;
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {

            string url = txtUrl.Text;
            var request = createRequest(url);
            HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
            int fileLen = int.Parse(webResponse.Headers["Content-Length"]);
            webResponse.Close();
            webResponse.Dispose();

            progressBarControl1.EditValue = 0;
            progressBarControl2.EditValue = 0;
            progressBarControl3.EditValue = 0;
            progressBarControl4.EditValue = 0;
            progressBarControl5.EditValue = 0;

            ProgressBarControl[] arr = { progressBarControl1,
                progressBarControl2,
                progressBarControl3 ,
                progressBarControl5};

            tastCount = 4;
            int avg_bytes = fileLen / tastCount + 1;
            int offset = 0;
            int remainingBytes = fileLen;
            filename = AppDomain.CurrentDomain.BaseDirectory + @"adown.exe";
            byte[] buff = new byte[fileLen];

            progressBarControl4.Properties.Maximum = fileLen;
            for (int i = 0; i < tastCount; i++)
            {
                int byteCount = Math.Min(avg_bytes, remainingBytes);
                remainingBytes -= byteCount;
                int start = offset;
                int end = start + byteCount - 1;
                offset += byteCount;
                ProgressBarControl bar = arr[i];
                bar.Properties.Maximum = byteCount;

                var partRequest = createRequest(url);
                partRequest.AddRange(start, end);



                Task.Factory.StartNew(() =>
                {
                    partRequest.BeginGetResponse(ias =>
                    {
                        var webResp = ((HttpWebRequest)ias.AsyncState).EndGetResponse(ias);

                        var respStream = webResp.GetResponseStream();
                        //respStream.Close();
                        DownloadPart(webResp, respStream, buff, start, byteCount, 0, bar);
                        //DownloadPart(webResp, respStream, new byte[byteCount], 0, byteCount, 0, bar);
                    }, partRequest);
                });

            }

        }
    }
}

DOWNLOAD SOURCE

HAVE FUN :)

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Tách file thành nhiều phần để download
Đăng bởi: Thảo Meo - Lượt xem: 9345 09:09:19, 16/04/2018DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.