Cách Zip nhiều files trong C#
Hôm nay Góc Kinh Nghiệm giới thiệu đến các bạn cách Zip nhiều files thành một file zip trong C#. Mô tả tình huống: Chúng ta có một thư mục thên Files, nằm trong ổ D: của máy tính. Thư mục này chứa 3 files, lần lược là: Product.txt, Customer.xls và Invoice.pdf. Chúng ta sẽ nén 3 files này thành ...
Hôm nay Góc Kinh Nghiệm giới thiệu đến các bạn cách Zip nhiều files thành một file zip trong C#.
Mô tả tình huống:
Chúng ta có một thư mục thên Files, nằm trong ổ D: của máy tính. Thư mục này chứa 3 files, lần lược là: Product.txt, Customer.xls và Invoice.pdf. Chúng ta sẽ nén 3 files này thành một file zip tên MyZipFile.zip và đặt file zip này trong thư mục Files. Cấu trúc các file cần nén như bên dưới:
D:Files D:FilesProduct.txt D:FilesCustomer.xls D:FilesInvoice.pdf
Bên dưới là các bước minh họa cho cách zip file:
- Bước 1: bạn lên google search và download dll tên ICSharpCode.SharpZipLib.dll
- Bước 2: mở Visual Studio lên, tạo project tên ZipFiles
- Bước 3: bạn nhấn chuột phải vào project, chọn “Add Reference …”, sau đó trỏ đến dll vừa download ở bước 1
- Bước 4: bạn code như bên dưới
using System.IO;
using System.Web;
using ICSharpCode.SharpZipLib.Zip;
namespace ZipFiles
{
public partial class Form : Form
{
public Form()
{
InitializeComponent();
}
private void btnZipFiles_Click(object sender, EventArgs e)
{
try
{
string directory = "D:\Files";
string[] files = Directory.GetFiles(directory);
string zipFile = "D:\Files\MyZipFile.zip";
ZipOutputStream zipOut = new ZipOutputStream(File.Create(zipFile));
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
ZipEntry entry = new ZipEntry(fileInfo.Name);
FileStream fileStream = File.OpenRead(file);
byte[] buffer = new byte[Convert.ToInt32(fileStream.Length)];
fileStream.Read(buffer, 0, (int)fileStream.Length);
entry.DateTime = fileInfo.LastWriteTime;
entry.Size = fileStream.Length;
fileStream.Close();
zipOut.PutNextEntry(entry);
zipOut.Write(buffer, 0, buffer.Length);
}
zipOut.Finish();
zipOut.Close();
MessageBox.Show("Thành công!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Chạy chương trình bạn thu được một file zip tên MyZipFile.zip trong D:Files chứa 3 tập tin cần zip như bên dưới.
D:Files D:FilesProduct.txt D:FilesCustomer.xls D:FilesInvoice.pdf D:FilesMyZipFile.zip
Góc Kinh Nghiệm chúc các bạn thành công! 
Tham khảo cách Zip files sử dụng tại DotNetZip đây