NEWS

[C#] Hướng dẫn copy file with Progress bar sử dụng Extension Method

[C#] Hướng dẫn copy file with Progress bar sử dụng Extension Method
Đăng bởi: Thảo Meo - Lượt xem: 11839 21:11:08, 26/10/2018DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách copy file with progress bar c# sử dụng Extension Method trong lập trình c#.

[C#] Tutorial Copy File With Progress bar

Trong nhiều trường hợp, nếu các bạn copy một file có dung lượng lớn, thì chúng ta cần phải thể hiện thanh progress thể hiện phần trăm công việc copy đang hoàn thành.

Trong bài viết này mình sẽ sử dụng Extension Method để hiện thị, các bạn có thể copy class này về để sử dụng theo ý của mình.

Giao diện copy file with progressbar c#:

copy_file_csharp
Demo app copy file with progress bar c#

Và dưới đây là video demo ứng dụng, mình thực hiện copy một file setup Ubuntu Linux khoảng 750MB.

Đầu tiên các bạn cần tạo cho mình một class với tên FileInfoExtensions.cs

Source code C#:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CopyFileWithProgressbar
{
    public static class  FileInfoExtensions
    {
        public static void CopyTo(this FileInfo file, FileInfo destination, Action<int> progressCallback)
        {
            const int bufferSize = 1024 * 1024;  //1MB
            byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];
            bool swap = false;
            int progress = 0, reportedProgress = 0, read = 0;
            long len = file.Length;
            float flen = len;
            Task writer = null;

            using (var source = file.OpenRead())
            using (var dest = destination.OpenWrite())
            {
                dest.SetLength(source.Length);
                for (long size = 0; size < len; size += read)
                {
                    if ((progress = ((int)((size / flen) * 100))) != reportedProgress)
                        progressCallback(reportedProgress = progress);
                    read = source.Read(swap ? buffer : buffer2, 0, bufferSize);
                    writer?.Wait(); 
                    writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);
                    swap = !swap;
                }
                writer?.Wait(); 
            }
        }

    }
}

Và tiếp theo là chúng ta viết source code cho Form1.cs

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

namespace CopyFileWithProgressbar
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void CopyFile()
        {
            var _source = new FileInfo(txt_source.Text);
            var _destination = new FileInfo(txt_des.Text);
            if (_destination.Exists)
                _destination.Delete();

            Task.Run(() =>
            {

                _source.CopyTo(_destination, x => progressBar1.BeginInvoke(new Action(() => { progressBar1.Value = x; lbl_percent.Text = x.ToString() + "%"; })));
            }).GetAwaiter().OnCompleted(() => progressBar1.BeginInvoke(new Action(() => { progressBar1.Value = 100; lbl_percent.Text = "100%"; MessageBox.Show("Copy file finish!"); })));
        }

        private void btn_copyfile_Click(object sender, EventArgs e)
        {
            CopyFile();
        }

    }
}

CHÚC CÁC BẠN THÀNH CÔNG!

DOWNLOAD SOURCE

 

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn copy file with Progress bar sử dụng Extension Method
Đăng bởi: Thảo Meo - Lượt xem: 11839 21:11:08, 26/10/2018DEVEXPRESS   In bài viết

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

Đọc tiếp
.