NEWS

[C#] Hướng dẫn sử dụng thư viện SharpZipLib nén và giải nén tập tin, thư mục Winform

[C#] Hướng dẫn sử dụng thư viện SharpZipLib  nén và giải nén tập tin, thư mục Winform
Đăng bởi: Thảo Meo - Lượt xem: 6268 09:18:53, 19/10/2020EBOOK

Xin chào các bạn, bài viết hôm nay mình sẻ giới thiệu các bạn sử dụng thư viện SharpZipLib dùng để nén và giải nén tập tin hoặc thư mục với các loại định dạng: Zip, GZip, Tar and BZip2.

[C#] Using SharpZipLib Compress and Decompress File or Folder

Trong winform đã có cung cấp cho chúng ta sẵn thư viện nén và giải nén tập tin với dạng chuẩn định dạng Zip.

Với thư viện SharpZipLib các bạn sẽ dễ dàng đặt mật khẩu cho file nén một cách dễ dàng.

Nếu bạn muốn sử dụng thư viện mặc định của Winform, các bạn có thể tham khảo bài viết này:

Nén File hoặc Folder using system.io.compression

Create-ZIP-in-C

Để cài đặt thư viện SharpZipLib, từ Nuget Console, các bạn chạy câu lệnh sau:

PM> Install-Package SharpZipLib -Version 1.3.0

Phiên bản mới nhất hiện tại mình viết bài là SharpZipLib 1.3.0

Để sử dụng thư viện các bạn cần import thư viện vào project C#:

using System.IO;
using ICSharpCode.SharpZipLib.Zip;

1. Hàm CompressDirectory nén nguyên một thư mục folder

private void CompressDirectory(string DirectoryPath, string OutputFilePath, int CompressionLevel = 9)
{
    try
    {
       string[] filenames = Directory.GetFiles(DirectoryPath);       
       using (ZipOutputStream OutputStream = new ZipOutputStream(File.Create(OutputFilePath)))
        {          
            OutputStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[4096];
            foreach (string file in filenames)
            {              
                ZipEntry entry = new ZipEntry(Path.GetFileName(file));              
                entry.DateTime = DateTime.Now;
                OutputStream.PutNextEntry(entry);

                using (FileStream fs = File.OpenRead(file))
                {                  
                    int sourceBytes;

                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        OutputStream.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }
            }

            OutputStream.Finish();           
            OutputStream.Close();
            Console.WriteLine("Files successfully compressed");
        }
    }
    catch (Exception ex)
    {       
        Console.WriteLine("Exception during processing {0}", ex);
    }
}

Cách sử dụng hàm trên:

CompressDirectory(
    @"C:\Users\user\Desktop\LaptrinhVB",
    @"C:\Users\user\Desktop\LaptrinhVB\nenfile.zip",
    9
);

Trong đó tham số nén compressLevel: các bạn chọn từ 0 => 9, chính là mức độ nén file 

2. Tạo password mật khẩu cho file nén

Nếu bạn muốn bảo vệ tập tin nén của mình, các bạn có thể sử dụng hàm dưới đây để đặt mật khẩu cho tập tin nén.

private void compressDirectoryWithPassword(string DirectoryPath, string OutputFilePath, string Password = null, int CompressionLevel = 9)
{
    try
    {            
        string[] filenames = Directory.GetFiles(DirectoryPath);        
        using (ZipOutputStream OutputStream = new ZipOutputStream(File.Create(OutputFilePath)))
        {           
            OutputStream.Password = Password;         
            OutputStream.SetLevel(CompressionLevel);

            byte[] buffer = new byte[4096];

            foreach (string file in filenames)
            {               
                ZipEntry entry = new ZipEntry(Path.GetFileName(file));                
                entry.DateTime = DateTime.Now;
                OutputStream.PutNextEntry(entry);

                using (FileStream fs = File.OpenRead(file))
                {                 
                    int sourceBytes;
                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        OutputStream.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }
            }         
          
            OutputStream.Finish();          
            OutputStream.Close();
            Console.WriteLine("Files successfully compressed");
        }
    }
    catch (Exception ex)
    {        
        Console.WriteLine("Exception during processing {0}", ex);
    }
}

Sử dụng hàm:

string PasswordZip = "laptrinhvb.net";

compressDirectoryWithPassword(
    @"C:\Users\laptrinhvb\Desktop\Folders",
    @"C:\Users\laptrinhvb\Desktop\Folders\filenen.zip",
    PasswordZip,
    9
);

3. Giải nén file zip

public void ExtractZipContent(string FileZipPath, string password, string OutputFolder)
{
    ZipFile file = null;
    try
    {
        FileStream fs = File.OpenRead(FileZipPath);
        file = new ZipFile(fs);

        if (!String.IsNullOrEmpty(password))
        {            
            file.Password = password;
        }

        foreach (ZipEntry zipEntry in file)
        {
            if (!zipEntry.IsFile)
            {               
                continue;           
            }

            String entryFileName = zipEntry.Name;          
            byte[] buffer = new byte[4096];     
            Stream zipStream = file.GetInputStream(zipEntry);          
            String fullZipToPath = Path.Combine(OutputFolder, entryFileName);
            string directoryName = Path.GetDirectoryName(fullZipToPath);

            if (directoryName.Length > 0)
            {
                Directory.CreateDirectory(directoryName);
            }
           
            using (FileStream streamWriter = File.Create(fullZipToPath))
            {
                StreamUtils.Copy(zipStream, streamWriter, buffer);
            }
        }
    }
    finally
    {
        if (file != null)
        {
            file.IsStreamOwner = true; 
            file.Close(); 
        }
    }
}

Cách sử dụng:

ExtractZipContent(
    @"C:\Users\laptrinhvb\Desktop\Folder\filenen.zip",
    "laptrinhvb",
    @"C:\Users\laptrinhvb\Desktop\outputfolder"
);

Thanks for watching!

 

Tags: sharpziplib c#zip file c#zip folder c#

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn sử dụng thư viện SharpZipLib  nén và giải nén tập tin, thư mục Winform
Đăng bởi: Thảo Meo - Lượt xem: 6268 09:18:53, 19/10/2020EBOOK