怎么在asp.net與C#中對文件進行解壓-創(chuàng)新互聯(lián)

本篇文章為大家展示了怎么在asp.net與C#中對文件進行解壓,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

創(chuàng)新互聯(lián)不只是一家網(wǎng)站建設的網(wǎng)絡公司;我們對營銷、技術、服務都有自己獨特見解,公司采取“創(chuàng)意+綜合+營銷”一體化的方式為您提供更專業(yè)的服務!我們經(jīng)歷的每一步也許不一定是最完美的,但每一步都有值得深思的意義。我們珍視每一份信任,關注我們的網(wǎng)站設計、成都做網(wǎng)站質量和服務品質,在得到用戶滿意的同時,也能得到同行業(yè)的專業(yè)認可,能夠為行業(yè)創(chuàng)新發(fā)展助力。未來將繼續(xù)專注于技術創(chuàng)新,服務升級,滿足企業(yè)一站式網(wǎng)絡營銷推廣需求,讓再小的成都品牌網(wǎng)站建設也能產(chǎn)生價值!

解壓縮單個文件:


復制代碼 代碼如下:

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, "解壓文件時發(fā)生錯誤:");
            }
            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;
                //判斷是否需要創(chuàng)建目錄
                if (!Directory.Exists(strDir))
                    bUnzipDir = (Directory.CreateDirectory(strDir) != null);
                else
                    bUnzipDir = true;
                //如果解壓目錄存在
                if (bUnzipDir)
                {
                    //獲得ZIP數(shù)據(jù)流
                    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,在/tupian/20230522/icsharpcode 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 != " " )                                                       
                    //創(chuàng)建根目錄下的子文件夾,不限制級別
                {
                    if (!Directory.Exists(fileDir + "\" + dir))
                    {
                        path = fileDir + "\" + dir;                                               
                        //在指定的路徑創(chuàng)建文件夾
                        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文件的基本步驟
                //基本思路就是遍歷壓縮文件里的所有文件,創(chuàng)建一個相同的文件。
                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與C#中對文件進行解壓,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

分享標題:怎么在asp.net與C#中對文件進行解壓-創(chuàng)新互聯(lián)
標題網(wǎng)址:http://www.bm7419.com/article30/ihdso.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供微信公眾號、響應式網(wǎng)站云服務器、移動網(wǎng)站建設、全網(wǎng)營銷推廣電子商務

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設