C#使用SharpZipLib类库压缩、解压缩单个文件

C#使用SharpZipLib类库压缩、解压缩单个文件,废话不说了,直接看代码吧,

类库下载地址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

/// 
/// 使用SharpZipLib压缩Zip文件
/// 
/// 源文件
/// 压缩后的Zip文件
/// 缓冲大小
public static void Zip(string srcFile, string dstFile, int bufferSize)
{
    using (FileStream fileStreamIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
    {
        using (FileStream fileStreamOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write))
        {
            using (ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut))
            {
                byte[] buffer = new byte[bufferSize];
                ZipEntry entry = new ZipEntry(Path.GetFileName(srcFile));
                zipOutStream.PutNextEntry(entry);
                int size;
                do
                {
                    size = fileStreamIn.Read(buffer, 0, buffer.Length);
                    zipOutStream.Write(buffer, 0, size);
                } while (size > 0);
                zipOutStream.Flush();
            }
        }
    }
}
 
/// 
/// 使用SharpZipLib解压缩Zip文件
/// 
/// Zip源文件
/// 解压出来的文件
/// 缓冲大小
public static void UnZip(string srcFile, string dstFile, int bufferSize)
{
    using (FileStream fileStreamIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
    {
        using (ZipInputStream zipInStream = new ZipInputStream(fileStreamIn))
        {
            ZipEntry entry = zipInStream.GetNextEntry();
            using (FileStream fileStreamOut = new FileStream(dstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write))
            {
                int size;
                byte[] buffer = new byte[bufferSize];
                do
                {
                    size = zipInStream.Read(buffer, 0, buffer.Length);
                    fileStreamOut.Write(buffer, 0, size);
                } while (size > 0);
                fileStreamOut.Flush();
            }
        }
    }
}
 
/// 
/// 测试Zip文件是否完整
/// 
/// Zip源文件
/// 
public static bool Test(string srcFile)
{
    bool flag = false;
    using (ZipFile zf = new ZipFile(srcFile))
    {
        flag = zf.TestArchive(true);
    }
    return flag;
}

你可能感兴趣的:(C#使用SharpZipLib类库压缩、解压缩单个文件)