Ví dụ chương trình download tập tin bằng C#

Trong Topic này Tôi muốn hướng dẫn các bạn cách viết chương trình download tập tin từ internet

Ở đây Tôi tạo 3 Project (ứng với 3 kiểu viết, Tôi tạm gọi vậy)

Ta sẽ kết hợp Progressbar để hiển thị quá trình download tập tin:

A) Dùng Window Form

B) Dùng WPF

=========================================================

Nếu như không biết cách cập nhập progressbar thì chương trình của bạn có thể bị treo, nó sẽ không cho phép bạn tương tác tới các control khác cho tới khi download xong.

Chúng ta phải viết code để giải quyết vấn đề này. Tức là chương trình load thì cứ load, ta tương tác với các control khác thì cứ tương tác:

Tôi có giải thích trong coding nên trong topic Tôi không giải thích thêm nữa

A) Dùng Window Form:

Form 1: Dùng  component BackgroundWorker

Ta sẽ dùng component BackgroundWorker, trường hợp này hơi “lằng nhằng” chút xíu, nếu bạn cảm thấy “khó chịu” thì hãy qua Form2 để xem Tôi không sử dụng component BackgroundWorker.

Sau khi thiết kế xong giao diện như trên, bạn kéo thả component BackgroundWorker vào winform như hình bên dưới:

Cấu hình BackgroundWorker như trên, sau đó bạn mở qua tab Event của BackgroundWorker:

Để có được các sự kiện như trên thì bạn chỉ cần double click vào tên từng sự kiện là tự động nó phát sinh ra cho bạn.

Bây giờ bạn xem coding behind:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

namespace ExampleBackgroundWorker

{

public partial class frmExample1 : Form

{

public frmExample1()

{

InitializeComponent();

}

private void btnTestDownload_Click(object sender, EventArgs e)

{

backgroundWorker1.RunWorkerAsync();

}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)

{

//Lấy đường dẫn muốn download

string sUrl =txtURL.Text.Trim();

//Đường dẫn lưu xuống ổ cứng

string sSave= txtSave.Text.Trim();

// Xác định dung lượng tập tin

Uri url = new Uri(sUrl);

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

response.Close();

// Lấy dung lượng tập tin

Int64 iSize = response.ContentLength;

// Khởi tạo dung lượng download được từ URL

Int64 iRunningByteTotal = 0;

// Dùng Webclient để download

WebClient client = new WebClient();

// Mở URL để download

Stream streamRemote = client.OpenRead(new Uri(sUrl));

// Vừa đọc vừa lưu

Stream streamLocal = new FileStream(sSave, FileMode.Create, FileAccess.Write, FileShare.None);

// Tiến hành loop quá trình download, vừa load vừa lưu

int iByteSize = 0;

byte[] byteBuffer = new byte[iSize];

while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)

{

// Lưu byte xuống đường dẫn chỉ định

streamLocal.Write(byteBuffer, 0, iByteSize);

iRunningByteTotal += iByteSize;//cập nhập số byte đã load được

// Chuyển đổi ra tỉ lệ 100%

double dIndex = (double)(iRunningByteTotal);

double dTotal = (double)byteBuffer.Length;

double dProgressPercentage = (dIndex / dTotal);

int iProgressPercentage = (int)(dProgressPercentage * 100);

// Cập nhập progressbar

backgroundWorker1.ReportProgress(iProgressPercentage);

}

streamLocal.Close();

streamRemote.Close();

}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)

{

progressBar1.Value = e.ProgressPercentage;

lblPercentage.Text = e.ProgressPercentage + “%”;

}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

MessageBox.Show(“Đã download xong!”);

}

}

}

Form 2: Không dùng  component BackgroundWorker

Thiết kế giao diện tương tự như Form 1, nhưng không kéo thả component BackgroundWorker

Các bạn xem coding bên dưới:

using System;using

System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Net;

namespace ExampleBackgroundWorker

{

public partial class frmExample2 : Form

{

public frmExample2()

{

InitializeComponent();

}

private void btnDownload_Click(object sender, EventArgs e)

{

WebClient wc = new WebClient();

wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);

wc.DownloadFileAsync(new Uri(txtURL.Text.Trim()), txtSave.Text);

wc.DownloadFileCompleted+=new AsyncCompletedEventHandler(wc_DownloadFileCompleted);

}

public void wc_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)

{

progressBar1.Value = e.ProgressPercentage;

lblPercentage.Text = e.ProgressPercentage + “%”;

}

public void wc_DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e)

{

MessageBox.Show(“Download is completed”);

}

}

}

Trường hợp này có vẻ đơn giản hơn 1 xíu:

B) Dùng WPF:

Thiết kế giao diện tương tự, các bạn tùy thích thiết kế, nhưng nhớ đặt tên control cho đúng với tên mà trong code Tôi lấy ra sử dụng

Bạn xem code, Tôi vẫn sử dụng WebClient.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.IO;

using System.Net;

namespace BackgroundWorker_WPF

{

/// <summary>

/// Interaction logic for MainWindow.xaml

/// </summary>

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void btnDownload_Click(object sender, RoutedEventArgs e)

{

WebClient wc = new WebClient();

wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);

wc.DownloadFileAsync(new Uri(txtURL.Text.Trim()), txtSave.Text);

wc.DownloadFileCompleted +=new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);

}

public void wc_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)

{

progressBar1.Value = e.ProgressPercentage;

lblPercentage.Content = e.ProgressPercentage + “%”;

}

public void wc_DownloadFileCompleted(Object sender, System.ComponentModel.AsyncCompletedEventArgs e)

{

MessageBox.Show(“Download is completed”);

}

}

}

Link code đầy đủ:http://www.mediafire.com/?202z1o7v8r3badi

Chúc các bạn thành công.

3 thoughts on “Ví dụ chương trình download tập tin bằng C#”

Leave a Reply