- [DEVEXPRESS] Hướng dẫn bật tính năng Scroll Pixcel in Touch trên GridView
- [DEVEXPRESS] Hướng dẫn sử dụng TileBar viết ứng dụng duyệt hình ảnh Winform
- [DEVEXPRESS] Tô màu border TextEdit trên Winform
- [C#] Lấy dữ liệu từ Console Write hiển thị lên textbox Winform
- [C#] Hiển thị Progress bar trên Window Console
- [C#] Di chuyển control Runtime và lưu layout trên winform
- [SQLSERVER] Sử dụng hàm NULL IF
- [C#] Chia sẽ source code mã đi tuần bằng giao diện Winform
- [C#] Flash Window in Taskbar Winform
- Download và Giải nén tập tin File sử dụng Powershell
- [C#] Hướng dẫn cách lấy thông tin đăng nhập tài khoản và mật khẩu web browser trên windows
- [VB.NET] CRUD Thêm xóa sửa tìm kiếm Realtime FireBase
- [C#] Hiển thị thông báo Toast Message trong lập trình Winform
- [C#] Cấu hình định dạng ngày tháng, thời gian trên Windows cho ứng dụng Winform
- [C#] Rút gọn đường dẫn link url với TinyURL API
- [C#] Hướng dẫn cách bo tròn winform with Radius
- [C#] Chia sẽ class BackGroundOverlay Show Modal cho Winform
- [C#] Hướng dẫn Flip Image Winform
- [C#] Invoke là gì? cách sử dụng phương thức Invoke()
- [C#] Hướng dẫn chia sẽ file, folder từ ứng dụng sang Zalo Chat
[C#] Tách file thành nhiều phần để download
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.
Dưới đây là demo mình download file Teamviewer C#
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);
});
}
}
}
}
HAVE FUN :)