02/10/2018, 20:44

Nén hoặc giải nén một file hay một thư mục

Khi lập trình có khi bạn gặp phải vấn đề là nén hoặc giải nén một file, một thư mục hoặc copy file hoặc thư mục. Trong bài viết này mình sẽ hướng dẫn các bạn sử dụng thư viện ICSharpCode.SharpZipLib để thực hiện điều đó Khi lập trình có khi bạn gặp phải vấn đề là nén ...

Khi lập trình có khi bạn gặp phải vấn đề là nén hoặc giải nén một file, một thư mục hoặc copy file hoặc thư mục. Trong bài viết này mình sẽ hướng dẫn các bạn sử dụng thư viện ICSharpCode.SharpZipLib để thực hiện điều đó

Khi lập trình có khi bạn gặp phải vấn đề là nén hoặc giải nén một file, một thư mục hoặc copy file hoặc thư mục. Trong bài viết này mình sẽ hướng dẫn các bạn sử dụng thư viện ICSharpCode.SharpZipLib để thực hiện điều đó

Lấy ví dụ một ứng dụng để bạn cần nén và copy file đã nén  là dữ liệu quan trọng của bạn chẳng hạn. Bạn có 1 Database có dữ liệu quan trọng cần backup hàng ngày và bạn đã đặt lịch backup định kỳ cho nó trong SQL, sau khi backup song  bạn cho thực hiện việc nén và copy file nén này sang một thuc mục khác hoặc sang một máy khác (cùng mạng Lan) đảm bảo an toàn dữ liệu hơn.

Trước tiên bạn cần download thư viện ICSharpCode.SharpZipLib tại đây.
Trong thư viện viện này cho phép bạn chọn các định dạng file nén, *.zip, *.rar, ... Trong bài này mình chỉ giới thiệu các bạn cách nén với định dang *.zip. Sau khi download về giải nén rồi bạn copy thư viện đó vào thư mục Bin của ứng dụng. Sau đây là các hàm thực hiện nén và giải nén.

1. Hàm nén các file trong một thư mục.

Để nén các gile trong thư mục bạn dùng hàm sau:

/// <summary> /// Create by: hungbv@hmweb.com.vn /// Nén tất các các files trong sPath vào fileZip /// </summary> /// <param name="sPath"></param> /// <param name="fileZip"></param> 
private static void NenMotThuMuc(string sPath, string fileZip) { ZipOutputStream zipOut = new ZipOutputStream(File.Create(fileZip)); foreach (string fName in Directory.GetFiles(sPath)) { FileInfo fi = new FileInfo(fName); ZipEntry entry = new ZipEntry(fi.Name); FileStream sReader = File.OpenRead(fName); byte[] buff = new byte[Convert.ToInt32(sReader.Length)]; sReader.Read(buff, 0, (int)sReader.Length); entry.DateTime = fi.LastWriteTime; entry.Size = sReader.Length; sReader.Close(); zipOut.PutNextEntry(entry); zipOut.Write(buff, 0, buff.Length); } zipOut.Finish(); zipOut.Close(); }


2. Hàm giải nén một file *.zip

Để giải nén một file.zip bạn thực hiện với hàm sau sẽ giải nén và đưa tất cả các gile trong file nén vào thư mục newFolder 

/// <summary> /// Create by: hungbv@hmweb.com.vn /// Giải nén một file.zip sFile vào thư mục newFolder /// </summary> /// <param name="sFile"></param> /// <param name="newFolder"></param> 
private static void GiaiNenMotFile(string sFile, string newFolder) { ZipInputStream zipIn = new ZipInputStream(File.OpenRead(sFile)); ZipEntry entry; while ((entry = zipIn.GetNextEntry()) != null) { FileStream streamWriter = File.Create(newFolder + entry.Name); long size = entry.Size; byte[] data = new byte[size]; while (true) { size = zipIn.Read(data, 0, data.Length); if (size > 0) streamWriter.Write(data, 0, (int)size); else break; } streamWriter.Close(); } }

Tiếp theo mình sẽ giới thiệu là hàm liệt kê tất cả các file có trong một file nén

3. Hàm trả về danh sách các file trong một file nén

 Để xem trong một file nén có những file nào bạn sử dụng hàm sau:

/// <summary> /// Trả về danh sách các file trong 1 file nén/// </summary> /// <param name="sFile"></param> /// <returns></returns> 
private static string ListZipContent(string sFile) { string listfilename = ""; ZipFile zip = new ZipFile(File.OpenRead(sFile)); foreach (ZipEntry entry in zip) { listfilename += entry.Name + "<br>"; } return listfilename; }
4. Hàm copy từ thư mục này đến thư mục khác

Để copy một thư mục, một file từ thư mục này đến thư mục khác bạn dụng hàm sau

/// <summary> /// Copy thư mục hoặc file từ thư mục này đến thư mục khác /// </summary> /// <param name="ThuMucNguon"></param> /// <param name="ThucMucDich"></param> 
public static void CopyDirectory(DirectoryInfo ThuMucNguon, DirectoryInfo ThucMucDich) { try { if (!ThucMucDich.Exists) { ThucMucDich.Create(); } FileInfo[] files = ThuMucNguon.GetFiles(); foreach (FileInfo file in files) { if ((System.IO.File.Exists(System.IO.Path.Combine(ThucMucDich.FullName, file.Name))) == false) { file.CopyTo(Path.Combine(ThucMucDich.FullName, file.Name)); } } //Xử lý thư mục con DirectoryInfo[] dirs = ThuMucNguon.GetDirectories(); foreach (DirectoryInfo dir in dirs) { string ThucMucDichDir = Path.Combine(ThucMucDich.FullName, dir.Name); CopyDirectory(dir, new DirectoryInfo(ThucMucDichDir)); } } catch { } }

Hàm trên chỉ copy thư mục hoặc file chưa có trong thư mục đích. Vậy muốn copy một file đã có triong thư mục địch bạn cần viết hàm khác. Hàm đó mình viết như sau:

5. Hàm copy từ thư mục này đến thư mục khác - Overwrite
private void CopyDirectory_Overwrite(string ThuMucNguonPath, string destPath, bool overwrite) { System.IO.DirectoryInfo ThuMucNguonDir = new System.IO.DirectoryInfo(ThuMucNguonPath); System.IO.DirectoryInfo destDir = new System.IO.DirectoryInfo(destPath); if (ThuMucNguonDir.Exists) { if (!destDir.Exists) destDir.Create(); foreach (System.IO.FileInfo file in ThuMucNguonDir.GetFiles()) { if (overwrite) file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name)); else if ((System.IO.File.Exists(System.IO.Path.Combine(destDir.FullName, file.Name))) == false) file.CopyTo(System.IO.Path.Combine(destDir.FullName, file.Name), false); } foreach (System.IO.DirectoryInfo dir in ThuMucNguonDir.GetDirectories()) { CopyDirectory_Overwrite(dir.FullName, System.IO.Path.Combine(destDir.FullName, dir.Name), overwrite); } } }


Vì dụ nhé trong ổ D của mình có một thư mục là flyout Giờ mình muốn nén thư mục này theo thành flyout+ddMMyyy.zip thì trong Page_Load (Hoặc trong sự kiện Onclick của bạn) mình chỉ cần gọi hàm như sau:

NenMotThuMuc(@"D:flyout", @"D:flyout" + DateTime.Now.ToString("ddMMyyyy") + ".zip");

Khi đó mình sẽ được file flyout05062010.zip. Tiếp theo mình sử dụng hàm ListZipContent để kiểm tra như sau:
Label1.Text = ListZipContent(@"D:flyout05062010.zip"); Sẽ cho kết quả là:
flyout.rar
index.html
style.css

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

Nguồn: http://www.thietkewebsmart.com/asp-net-csharp/nen-hoac-giai-nen-mot-file-hay-mot-thu-muc/656.htm

Bình luận
0