C#压缩打包文件

该控件是使用csharp写的,因此可以直接在dotnet环境中引用,不需要注册。

利用 SharpZipLib方便地压缩和解压缩文件
最新版本的SharpZipLib(0.84)增加了很多新的功能,其中包括增加了FastZip类,这让我们可以非常方便地把一个目录压缩成一个压缩包,经测试可以很好地支持文件中包含中文以及空格的情况。

压缩:

/// <summary>
/// 创建Zip对象
/// </summary>
/// <param name="filename">文件名.</param>
/// <param name="directory">将要压缩的目录.</param>
public static void ZipFile(string filename, string directory)
{
    try
    {
        FastZip fz = new FastZip();
        fz.CreateEmptyDirectories = true;
        fz.CreateZip(filename, directory, true, "");
        fz = null;
    }
    catch (Exception)
    {
        throw;
    }
}

解压缩:

/// <summary>
/// 解压缩.
/// </summary>
/// <param name="file">文件.</param>
/// <returns>解压成功返回true,否则false</returns>
public static bool UnpackFiles(string file, string dir)
{
    try
    {
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        ZipInputStream s = new ZipInputStream(File.OpenRead(file));

        ZipEntry theEntry;
        while ((theEntry = s.GetNextEntry()) != null)
        {

            string directoryName = Path.GetDirectoryName(theEntry.Name);
            string fileName = Path.GetFileName(theEntry.Name);

            if (directoryName != String.Empty)
                Directory.CreateDirectory(dir + directoryName);

            if (fileName != String.Empty)
            {
                FileStream streamWriter = File.Create(dir + theEntry.Name);

                int size = 2048;
                byte[] data = new byte[2048];
                while (true)
                {
                    size = s.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }

                streamWriter.Close();
            }
        }
        s.Close();
        return true;
    }
    catch (Exception)
    {
        throw;
    }
}

以下是SharpZipLib的另一种方法,其中方法全:

 /// <summary>
/// 压缩和解压文件
/// </summary>
public class ZipClass
{
    /// <summary>
    /// 所有文件缓存
    /// </summary>
    List<string> files = new List<string>();

    /// <summary>
    /// 所有空目录缓存
    /// </summary>
    List<string> paths = new List<string>();

    /// <summary>
    /// 压缩单个文件
    /// </summary>
    /// <param name="fileToZip">要压缩的文件</param>
    /// <param name="zipedFile">压缩后的文件全名</param>
    /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
    /// <param name="blockSize">分块大小</param>
    public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
    {
        if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
        {
            throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
        }

        FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
        FileStream zipFile = File.Create(zipedFile);
        ZipOutputStream zipStream = new ZipOutputStream(zipFile);
        ZipEntry zipEntry = new ZipEntry(fileToZip);
        zipStream.PutNextEntry(zipEntry);
        zipStream.SetLevel(compressionLevel);
        byte[] buffer = new byte[blockSize];
        int size = streamToZip.Read(buffer, 0, buffer.Length);
        zipStream.Write(buffer, 0, size);

        try
        {
            while (size < streamToZip.Length)
            {
                int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                zipStream.Write(buffer, 0, sizeRead);
                size += sizeRead;
            }
        }
        catch (Exception ex)
        {
            GC.Collect();
            throw ex;
        }

        zipStream.Finish();
        zipStream.Close();
        streamToZip.Close();
        GC.Collect();
    }

    /// <summary>
    /// 压缩目录(包括子目录及所有文件)
    /// </summary>
    /// <param name="rootPath">要压缩的根目录</param>
    /// <param name="destinationPath">保存路径</param>
    /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
    public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
    {
        GetAllDirectories(rootPath);

        /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾
        {

        rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\"

        }
        */
        //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
        string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
        Crc32 crc = new Crc32();
        ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
        outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
        foreach (string file in files)
        {
            FileStream fileStream = File.OpenRead(file);//打开压缩文件
            byte[] buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
            entry.DateTime = DateTime.Now;
            // set Size and the crc, because the information
            // about the size and crc should be stored in the header
            // if it is not set it is automatically written in the footer.
            // (in this case size == crc == -1 in the header)
            // Some ZIP programs have problems with zip files that don‘t store
            // the size and crc in the header.
            entry.Size = fileStream.Length;
            fileStream.Close();
            crc.Reset();
            crc.Update(buffer);
            entry.Crc = crc.Value;
            outPutStream.PutNextEntry(entry);
            outPutStream.Write(buffer, 0, buffer.Length);
        }

        this.files.Clear();

        foreach (string emptyPath in paths)
        {
            ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
            outPutStream.PutNextEntry(entry);
        }

        this.paths.Clear();
        outPutStream.Finish();
        outPutStream.Close();
        GC.Collect();
    }

    /// <summary>
    /// 取得目录下所有文件及文件夹,分别存入files及paths
    /// </summary>
    /// <param name="rootPath">根目录</param>
    private void GetAllDirectories(string rootPath)
    {
        string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
        foreach (string path in subPaths)
        {
            GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
        }
        string[] files = Directory.GetFiles(rootPath);
        foreach (string file in files)
        {
            this.files.Add(file);//将当前目录中的所有文件全名存入文件List
        }
        if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录
        {
            this.paths.Add(rootPath);//记录空目录
        }
    }

    /// <summary>
    /// 解压缩文件(压缩文件中含有子目录)
    /// </summary>
    /// <param name="zipfilepath">待解压缩的文件路径</param>
    /// <param name="unzippath">解压缩到指定目录</param>
    /// <returns>解压后的文件列表</returns>
    public List<string> UnZip(string zipfilepath, string unzippath)
    {
        //解压出来的文件列表
        List<string> unzipFiles = new List<string>();

        //检查输出目录是否以“\\”结尾
        if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
        {
            unzippath += "\\";
        }

        ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
        ZipEntry theEntry;
        while ((theEntry = s.GetNextEntry()) != null)
        {
            string directoryName = Path.GetDirectoryName(unzippath);
            string fileName = Path.GetFileName(theEntry.Name);

            //生成解压目录【用户解压到硬盘根目录时,不需要创建】
            if (!string.IsNullOrEmpty(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            if (fileName != String.Empty)
            {
                //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
                if (theEntry.CompressedSize == 0)
                    break;
                //解压文件到指定的目录
                directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
                //建立下面的目录和子目录
                Directory.CreateDirectory(directoryName);

                //记录导出的文件
                unzipFiles.Add(unzippath + theEntry.Name);

                FileStream streamWriter = File.Create(unzippath + theEntry.Name);

                int size = 2048;
                byte[] data = new byte[2048];
                while (true)
                {
                    size = s.Read(data, 0, data.Length);
                    if (size > 0)
                    {
                        streamWriter.Write(data, 0, size);
                    }
                    else
                    {
                        break;
                    }
                }
                streamWriter.Close();
            }
        }
        s.Close();
        GC.Collect();
        return unzipFiles;
    }
}
时间: 2024-08-11 08:46:50

C#压缩打包文件的相关文章

[转]C#压缩打包文件

/// <summary> /// 压缩和解压文件 /// </summary> public class ZipClass { /// <summary> /// 所有文件缓存 /// </summary> List<string> files = new List<string>(); /// <summary> /// 所有空目录缓存 /// </summary> List<string> p

java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹

一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry  ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.

java.util.zip压缩打包文件总结二: ZIP解压技术

一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: CheckedInputStream cis = new CheckedInputStream(new FileInputStream( srcFile), new CRC32()); ZipInputStream zis = new ZipInputStream(cis); 需要注意的是,在构建解压文件时,需要

C# 压缩打包文件下载

C# 压缩打包文件下载 public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform { #region INameTransform 成员 public string TransformDirectory(string name) { return null; } public string TransformFile(string name) { return Path.GetFileName(name);

压缩打包介绍 gzip bzip2 xz压缩工具

一.压缩打包介绍 压缩打包文件对磁盘来讲,节省空间,对传输来讲,传输速度变短,带宽资源耗费减少 二.gzip压缩工具#find /etc/ -type f -name "*.conf" -exec cat {} >> 1.txt \;// 查找/etc/下的所有.conf文件并把cat出来的所有.conf文件追加到1.txt中 gzip压缩:(不能压缩目录)#gzip filename //压缩完成之后文件名称变为:filename.gz格式gzip解压:#gzip -d

Linux下压缩某个文件夹(文件夹打包)

tar -zcvf /home/xahot.tar.gz /xahottar -zcvf 打包后生成的文件名全路径 要打包的目录 例子:把/xahot文件夹打包后生成一个/home/xahot.tar.gz的文件.zip 压缩方法:压缩当前的文件夹 zip -r ./xahot.zip ./* -r表示递归zip [参数] [打包后的文件名] [打包的目录路径]解压 unzip xahot.zip 不解释linux zip命令的基本用法是:linux zip命令参数列表:-a 将文件转成ASCI

albert1017 Linux下压缩某个文件夹(文件夹打包)

tar -zcvf /home/xahot.tar.gz /xahottar -zcvf 打包后生成的文件名全路径 要打包的目录例子:把/xahot文件夹打包后生成一个/home/xahot.tar.gz的文件. # tar -xf all.tar 这条命令是解出all.tar包中所有文件,-x是解开的意思 zip 压缩方法: 压缩当前的文件夹 zip -r ./xahot.zip ./* -r表示递归zip [参数] [打包后的文件名] [打包的目录路径]解压 unzip xahot.zip

文件查找和压缩打包

作业1 编写一个脚本/root/bin/createuser.sh,脚本的执行语法必须是:createuser.sh -u username -m password,选项与参数间可支持多空格,但不能顺序颠倒. 当未指定正确的选项或参数时,以错误输出方式提示"createuser.sh -u username -m password "后退出脚本. 用户名必须以字母开头,可包括数字和_.否则不合法.以错误输出提示用户"用户名仅包含字母数据和下划线" 当用户名检测合法后

linux的tar命令详情;linux多个文件压缩打包到一个压缩文件

tar命令 可以用来压缩打包单文件.多个文件.单个目录.多个目录. Linux打包命令_tar tar命令可以用来压缩打包单文件.多个文件.单个目录.多个目录. 常用格式: 单个文件压缩打包 tar czvf my.tar.gz file1 多个文件压缩打包 tar czvf my.tar.gz file1 file2,...(file*)(也可以给file*文件mv 目录在压缩) 单个目录压缩打包 tar czvf my.tar.gz dir1 多个目录压缩打包 tar czvf my.tar