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

这篇文章主要介绍了asp.net C#实现解压缩文件的方法,分别讲述了三种不同的实现方法,是非常实用的技巧,需要的朋友可以参考下

本文实例讲述了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
{
    ///
    /// 解压缩类
    ///

   public static class ZIP
    {
        ///
        /// 解压ZIP文件包
        ///

        /// ZIP文件路径
        /// 解压后的文件目录路径
        /// 是否解压成功
        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;
///
/// ZipFloClass 的摘要说明
///

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);
            }
        }
    }
}

以上就是asp.net C#实现解压缩文件的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » ASP编程