C# 压缩、解压文件

1.引用ICSharpCode.SharpZipLib.dll类库

public class ZipFile
    {
        public static byte[] bytes;
        ///压缩文件
        //strFilePath 待压缩文件全路径
        //strZipPath 输出压缩文件全路径 .zip结尾
        public static void FileToZip(string strFilePath, string strZipPath)
        {
            try
            {
                string strFileFullName = strFilePath.Substring(strFilePath.LastIndexOf("\\") + 1);
                FileStream StreamToZip = new FileStream(strFilePath, FileMode.Open, FileAccess.Read);
                FileStream ZipFile = File.Create(strZipPath);
                ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
                //压缩文件
                ZipEntry ZipEntry = new ZipEntry(strFileFullName);
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(6);
                byte[] buffer = new byte[StreamToZip.Length];
                StreamToZip.Read(buffer, 0, Convert.ToInt32(StreamToZip.Length));
                ZipStream.Write(buffer, 0, Convert.ToInt32(StreamToZip.Length));
                ZipStream.Finish();
                ZipStream.Close();
                StreamToZip.Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    //解压文件
    //strZipPath 压缩文件全路径
    //strAddress 解压路径 不带\\ 不带解压名
    public static void ZipToFile(string strZipPath, string strAddress)
    {
        try
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(strZipPath));
            ZipEntry fileEntry;
            while ((fileEntry = s.GetNextEntry()) != null)
            {
                string strFileFullName = Path.GetFileName(fileEntry.Name);
                if (strFileFullName != "")
                {
                    strFileFullName = strAddress + "\\" + strFileFullName;
                    FileStream streamWriter = File.Create(strFileFullName);
                    int size = 2048;
                    byte[] buffer = new byte[s.Length];
                    size = s.Read(buffer, 0, buffer.Length);
                    streamWriter.Write(buffer, 0, size);
                    streamWriter.Close();
                }
            }
            s.Close();
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message, "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }

    /// <summary>
    /// 压缩文件夹
    /// </summary>
    /// <param name="dirPath">压缩文件夹的路径</param>
    /// <param name="fileName">生成的zip文件路径</param>
    /// <param name="level">压缩级别 0 - 9 0是存储级别 9是最大压缩</param>
    /// <param name="bufferSize">读取文件的缓冲区大小</param>
    public static void FolderToZip(string dirPath, string fileName, int level, int bufferSize)
    {
        try
        {
            byte[] buffer = new byte[bufferSize];
            using (ZipOutputStream s = new ZipOutputStream(File.Create(fileName)))
            {
                s.SetLevel(level);
                CompressDirectory(dirPath, dirPath, s, buffer);
                s.Finish();
                s.Close();
            }
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message, "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }
    /// <summary>
    /// 压缩多文件到zip压缩文件
    /// </summary>
    /// <param name="needZipfiles">待压缩文件列表</param>
    /// <param name="zipFileName">目标压缩文件</param>
    /// <param name="relativeDir">zip压缩文件中的相对路径</param>
    /// <param name="level">压缩级别</param>
    /// <param name="bufferSize">读取文件缓冲大小</param>
    public static void FilesToZip(List<string> needZipfiles, string zipFileName, string relativeDir, int level, int bufferSize)
    {
        try
        {
            if (needZipfiles.Count < 1) return;

            byte[] buffer = new byte[bufferSize];
            if (!string.IsNullOrEmpty(relativeDir))
            {
                relativeDir += "\\";
            }
            int sourceBytes = 0;
            using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName)))
            {
                s.SetLevel(level);
                foreach (string file in needZipfiles)
                {
                    ZipEntry entry = new ZipEntry(relativeDir + Path.GetFileName(file));
                    entry.DateTime = DateTime.Now;
                    s.PutNextEntry(entry);
                    using (FileStream fs = File.OpenRead(file))
                    {
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            s.Write(buffer, 0, sourceBytes);
                        } while (sourceBytes > 0);
                    }
                }
                s.Finish();
                s.Close();
            }
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.Message);
            MessageBox.Show(ex.Message, "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }

    /// <summary>
    /// 压缩文件夹
    /// </summary>
    /// <param name="root">压缩文件夹路径</param>
    /// <param name="path">压缩文件夹内当前要压缩的文件夹路径</param>
    /// <param name="s"></param>
    /// <param name="buffer">读取文件的缓冲区大小</param>
    private static void CompressDirectory(string root, string path, ZipOutputStream s, byte[] buffer)
    {
        string relativePath = root.Substring(root.LastIndexOf("\\") + 1);
        relativePath += "\\";
        string[] fileNames = Directory.GetFiles(path);
        string[] dirNames = Directory.GetDirectories(path);
        int sourceBytes;
        foreach (string file in fileNames)
        {
            ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(file));
            entry.DateTime = DateTime.Now;
            s.PutNextEntry(entry);
            using (FileStream fs = File.OpenRead(file))
            {
                do
                {
                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                    s.Write(buffer, 0, sourceBytes);
                } while (sourceBytes > 0);
            }
        }

        foreach (string dirName in dirNames)
        {
            string relativeDirPath = dirName.Replace(root, "");
            ZipEntry entry = new ZipEntry(relativeDirPath.Replace("\\", "/") + "/");
            s.PutNextEntry(entry);
            CompressDirectory(root, dirName, s, buffer);
        }
    }


    /// <summary>
    /// 解压缩zip目录
    /// </summary>
    /// <param name="zipFilePath">解压的zip文件路径</param>
    /// <param name="extractPath">解压到的文件夹路径</param>
    /// <param name="bufferSize">读取文件的缓冲区大小</param>
    public static void ZipToFolder(string zipFilePath, string extractPath, int bufferSize)
    {
        try
        {
            extractPath += "//";
            byte[] data = new byte[bufferSize];
            int size;
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry entry;
                while ((entry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(entry.Name);
                    string fileName = Path.GetFileName(entry.Name);

                    //先创建目录
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(extractPath + directoryName);

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(extractPath + entry.Name.Replace("/", "//")))
                        {
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                    streamWriter.Write(data, 0, size);
                                else
                                    break;
                            }
                        }
                    }
                }
            }
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// 解压zip文件到指定目录,适用于电力版绑定下载
    /// </summary>
    /// <param name="zipFilePath">zip</param>
    /// <param name="extractPath"></param>
    /// <param name="bufferSize"></param>
    /// <param name="filesExistPrompt"></param>
    /// <param name="bar"></param>
    public static void ZipToFolder(string zipFilePath, string extractPath, int bufferSize,
        bool filesExistPrompt = false)
    {
        try
        {
            extractPath += "\\";
            byte[] data = new byte[bufferSize];
            int size;
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry entry;
                while ((entry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(entry.Name);
                    string fileName = Path.GetFileName(entry.Name);
                    if (filesExistPrompt)
                    {
                        if (File.Exists(extractPath + entry.Name))
                        {
                            var res = MessageBox.Show("'" + extractPath + entry.Name + "'已存在,是否覆盖?", "提示",
                                  MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (res != DialogResult.Yes) continue;
                        }
                    }
                    //先创建目录
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(extractPath + directoryName);

                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(extractPath + entry.Name.Replace("/", "//")))
                        {
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                    streamWriter.Write(data, 0, size);
                                else
                                    break;
                            }
                        }
                    }
                }
            }
            if (File.Exists(zipFilePath))
                File.Delete(zipFilePath);
        }
        catch (System.Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.Message);
            throw ex;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值