asp.net C#实现解压缩文件的方法

 更新时间:2021年9月22日 10:11  点击:2249

本文实例讲述了asp.net C#实现解压缩文件的方法。一共给大家介绍了三段代码,一个是简单的解压缩单个zip文件,后一个可以解压批量的大量的但需要调用ICSharpCode.SharpZipLib.dll类了,最后一个比较实例可压缩也可以解压缩了分享给大家供大家参考。具体如下:

解压缩单个文件:

复制代码 代码如下:
using System.IO;
using System.IO.Compression;
string sourceFile=@"D:2.zip";
string destinationFile=@"D:1.txt";
        private const long BUFFER_SIZE = 20480;
            // make sure the source file is there
            if (File.Exists ( sourceFile ))
            {
            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream decompressedStream = null;
            byte[] quartetBuffer = null;
            try
            {
                // Read in the compressed source stream
                sourceStream = new FileStream ( sourceFile, FileMode.Open );
                // Create a compression stream pointing to the destiantion stream
                decompressedStream = new DeflateStream ( sourceStream, CompressionMode.Decompress, true );
                // Read the footer to determine the length of the destiantion file
                quartetBuffer = new byte[4];
                int position = (int)sourceStream.Length - 4;
                sourceStream.Position = position;
                sourceStream.Read ( quartetBuffer, 0, 4 );
                sourceStream.Position = 0;
                int checkLength = BitConverter.ToInt32 ( quartetBuffer, 0 );
                byte[] buffer = new byte[checkLength + 100];
                int offset = 0;
                int total = 0;
                // Read the compressed data into the buffer
                while ( true )
                {
                    int bytesRead = decompressedStream.Read ( buffer, offset, 100 );
                    if ( bytesRead == 0 )
                        break;
                    offset += bytesRead;
                    total += bytesRead;
                }
                // Now write everything to the destination file
                destinationStream = new FileStream ( destinationFile, FileMode.Create );
                destinationStream.Write ( buffer, 0, total );
                // and flush everyhting to clean out the buffer
                destinationStream.Flush ( );
            }
            catch ( ApplicationException ex )
            {
                Console.WriteLine(ex.Message, "解压文件时发生错误:");
            }
            finally
            {
                // Make sure we allways close all streams
                if ( sourceStream != null )
                    sourceStream.Close ( );
                if ( decompressedStream != null )
                    decompressedStream.Close ( );
                if ( destinationStream != null )
                    destinationStream.Close ( );
            }
}

批量解压缩(这需要调用一个解压缩类库。。 ICSharpCode.SharpZipLib.dll)

复制代码 代码如下:
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
namespace ZipLib
{
    /// <summary>
    /// 解压缩类
    /// </summary>
   public static class ZIP
    {
        /// <summary>
        /// 解压ZIP文件包
        /// </summary>
        /// <param name="strZipFile">ZIP文件路径</param>
        /// <param name="strDir">解压后的文件目录路径</param>
        /// <returns>是否解压成功</returns>
        public static bool unzipFiles(string strZipFile, string strDir)
        {
            //判断ZIP文件是否存在
            if (File.Exists(strZipFile))
            {
                //判断目录是否存在
                bool bUnzipDir = false;
                //判断是否需要创建目录
                if (!Directory.Exists(strDir))
                    bUnzipDir = (Directory.CreateDirectory(strDir) != null);
                else
                    bUnzipDir = true;
                //如果解压目录存在
                if (bUnzipDir)
                {
                    //获得ZIP数据流
                    ZipInputStream zipStream = new ZipInputStream(File.OpenRead(strZipFile));
                    if (zipStream != null)
                    {
                        ZipEntry zipEntry = null;
                        while ((zipEntry = zipStream.GetNextEntry()) != null)
                        {
                            string strUnzipFile = strDir + "//" + zipEntry.Name;
                            string strFileName = Path.GetFileName(strUnzipFile);
                            string strDirName = Path.GetDirectoryName(strUnzipFile);
                            //是否为解压目录
                            if (!string.IsNullOrEmpty(strDirName))
                                Directory.CreateDirectory(strDirName);
                            //是否为解压文件
                            if (!string.IsNullOrEmpty(strFileName))
                            {
                                //解压文件
                                FileStream unzipFileStream = new FileStream(strUnzipFile, FileMode.Create);
                                if (unzipFileStream != null)
                                {
                                    byte[] buf = new byte[2048];
                                    int size = 0;
                                    while ((size = zipStream.Read(buf, 0, 2048)) > 0)
                                        unzipFileStream.Write(buf, 0, size);
                                    //关闭Stream
                                    unzipFileStream.Flush();
                                    unzipFileStream.Close();
                                }
                            }
                        }
                        //关闭ZIP流
                        zipStream.Close();
                        //返回值
                        return true;
                    }
                }
            }
            return false;
        }
    }
}

上面两个都是解压缩文件,下面我们把压缩与解压缩放在一个实例中。
最近要做一个项目涉及到C#中压缩与解压缩的问题的解决方法,大家分享。
这里主要解决文件夹包含文件夹的解压缩问题。

下载SharpZipLib.dll,在http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx中有最新免费版本,“Assemblies for .NET 1.1, .NET 2.0, .NET CF 1.0, .NET CF 2.0: Download [297 KB] ”点击Download可以下载,解压后里边有好多文件夹,因为不同的版本,我用的FW2.0。
或者点击此处本站下载。

引用SharpZipLib.dll,在项目中点击项目右键-->添加引用-->浏览,找到要添加的DLL-->确认

改写了文件压缩和解压缩的两个类,新建两个类名字为ZipFloClass.cs,UnZipFloClass.cs
源码如下

复制代码 代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
/// <summary>
/// ZipFloClass 的摘要说明
/// </summary>
public class ZipFloClass
{
    public void ZipFile(string strFile, string strZip)
    {
        if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
            strFile += Path.DirectorySeparatorChar;
        ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
        s.SetLevel(6); // 0 - store only to 9 - means best compression
        zip(strFile, s, strFile);
        s.Finish();
        s.Close();
    }

    private void zip(string strFile, ZipOutputStream s, string staticFile)
    {
        if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
        Crc32 crc = new Crc32();
        string[] filenames = Directory.GetFileSystemEntries(strFile);
        foreach (string file in filenames)
        {
            if (Directory.Exists(file))
            {
                zip(file, s, staticFile);
            }
            else // 否则直接压缩文件
            {
                //打开压缩文件
                FileStream fs = File.OpenRead(file);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                string tempfile = file.Substring(staticFile.LastIndexOf("\") + 1);
                ZipEntry entry = new ZipEntry(tempfile);
                entry.DateTime = DateTime.Now;
                entry.Size = fs.Length;
                fs.Close();
                crc.Reset();
                crc.Update(buffer);
                entry.Crc = crc.Value;
                s.PutNextEntry(entry);
                s.Write(buffer, 0, buffer.Length);
            }
        }
    }
}

复制代码 代码如下:
using System;
using System.Data;
using System.Web;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Checksums;

/// <summary>
/// UnZipFloClass 的摘要说明
/// </summary>
public class UnZipFloClass
{
    public string unZipFile(string TargetFile, string fileDir)
    {
        string rootFile = " ";
        try
        {
            //读取压缩文件(zip文件),准备解压缩
            ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
            ZipEntry theEntry;
            string path = fileDir;                  
            //解压出来的文件保存的路径
            string rootDir = " ";                       
            //根目录下的第一个子文件夹的名称
            while ((theEntry = s.GetNextEntry()) != null)
            {
                rootDir = Path.GetDirectoryName(theEntry.Name);                         
                //得到根目录下的第一级子文件夹的名称
                if (rootDir.IndexOf("\") >= 0)
                {
                    rootDir = rootDir.Substring(0, rootDir.IndexOf("\") + 1);
                }
                string dir = Path.GetDirectoryName(theEntry.Name);                   
                //根目录下的第一级子文件夹的下的文件夹的名称
                string fileName = Path.GetFileName(theEntry.Name);                   
                //根目录下的文件名称
                if (dir != " " )                                                       
                    //创建根目录下的子文件夹,不限制级别
                {
                    if (!Directory.Exists(fileDir + "\" + dir))
                    {
                        path = fileDir + "\" + dir;                                               
                        //在指定的路径创建文件夹
                        Directory.CreateDirectory(path);
                    }
                }
                else if (dir == " " && fileName != "")                                            
                    //根目录下的文件
                {
                    path = fileDir;
                    rootFile = fileName;
                }
                else if (dir != " " && fileName != "")                                            
                    //根目录下的第一级子文件夹下的文件
                {
                    if (dir.IndexOf("\") > 0)                                                           
                        //指定文件保存的路径
                    {
                        path = fileDir + "\" + dir;
                    }
                }
                if (dir == rootDir)                                                                                 
                    //判断是不是需要保存在根目录下的文件
                {
                    path = fileDir + "\" + rootDir;
                }
                //以下为解压缩zip文件的基本步骤
                //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                if (fileName != String.Empty)
                {
                    FileStream streamWriter = File.Create(path + "\" + fileName);
                    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 rootFile;
        }
        catch (Exception ex)
        {
            return "1; " + ex.Message;
        }
    }  
}


引用,新建一个页面,添加两个按钮,为按钮添加Click事件
源码如下

复制代码 代码如下:
protected void Button1_Click(object sender, EventArgs e)
{
        string[] FileProperties = new string[2];
        FileProperties[0] = "D:\unzipped\";//待压缩文件目录
        FileProperties[1] = "D:\zip\a.zip";  //压缩后的目标文件
        ZipFloClass Zc = new ZipFloClass();
        Zc.ZipFile(FileProperties[0], FileProperties[1]);
}
protected void Button2_Click(object sender, EventArgs e)
{
        string[] FileProperties = new string[2];
        FileProperties[0] = "D:\zip\b.zip";//待解压的文件
        FileProperties[1] = "D:\unzipped\";//解压后放置的目标目录
        UnZipFloClass UnZc = new UnZipFloClass();
        UnZc.unZipFile(FileProperties[0], FileProperties[1]);
}

希望本文所述对大家的asp.net程序设计有所帮助。

[!--infotagslink--]

相关文章

  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • C#绘制曲线图的方法

    这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 经典实例讲解C#递归算法

    这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25