asp.net C realizes the method of decompressing files

  • 2021-01-22 05:04:54
  • OfStack

This article describes the example of asp.net C# to achieve the method of decompressing files. 1 to introduce a total of three sections of code, one is a simple decompression of a single zip file, the last one can decompress a large number of batch but need to call ICSharpCode.SharpZipLib.dll class, the last one comparison example can be compressed can also decompression to share for your reference. The details are as follows:

Unzip a single file:

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, " An error occurred while extracting the file: ");
            }
            finally
            {
                // Make sure we allways close all streams
                if ( sourceStream != null )
                    sourceStream.Close ( );
                if ( decompressedStream != null )
                    decompressedStream.Close ( );
                if ( destinationStream != null )
                    destinationStream.Close ( );
            }
}

Bulk decompression (this requires a call to a decompression library. ICSharpCode.SharpZipLib.dll)

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
namespace ZipLib
{
    /// <summary>
    /// Unzip the class
    /// </summary>
   public static class ZIP
    {
        /// <summary>
        /// Unpack the ZIP package
        /// </summary>
        /// <param name="strZipFile">ZIP The file path </param>
        /// <param name="strDir"> Path to the unzipped file directory </param>
        /// <returns> Whether the decompression was successful </returns>
        public static bool unzipFiles(string strZipFile, string strDir)
        {
            // judge ZIP Whether the file exists
            if (File.Exists(strZipFile))
            {
                // Determine whether the directory exists
                bool bUnzipDir = false;
                // Determine if the directory needs to be created
                if (!Directory.Exists(strDir))
                    bUnzipDir = (Directory.CreateDirectory(strDir) != null);
                else
                    bUnzipDir = true;
                // If the unzip directory exists
                if (bUnzipDir)
                {
                    // To obtain ZIP The data flow
                    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);
                            // Whether to extract the directory
                            if (!string.IsNullOrEmpty(strDirName))
                                Directory.CreateDirectory(strDirName);
                            // Whether to extract the file
                            if (!string.IsNullOrEmpty(strFileName))
                            {
                                // Unzip the files
                                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);
                                    // Shut down Stream
                                    unzipFileStream.Flush();
                                    unzipFileStream.Close();
                                }
                            }
                        }
                        // Shut down ZIP flow
                        zipStream.Close();
                        // The return value
                        return true;
                    }
                }
            }
            return false;
        }
    }
}

The above two are unzipped files, now let's scale the compression and unzipping in one instance.
Recently I want to do a project involving C# compression and decompression of the problem of the solution, we share.
Here is mainly to solve the folder containing folder decompression problem.

Download SharpZipLib. dll in http: / / www icsharpcode. net OpenSource/SharpZipLib/Download aspx have the latest version for free, "Assemblies for. NET 1.1, the NET 2.0, the NET CF 1.0, the NET CF 2.0: Download [297 KB] "Click Download to download, there are a lot of folders after unzip, because of different versions, I use FW2.0.
Or click here to download it.

To reference SharpZipLib. dll, right-click the project in the project -- > Add a reference -- > Browse to find the DLL-- to add > confirm

Rewrite the file compression and decompression of two classes, two class name for the new ZipFloClass. cs, UnZipFloClass. cs
The source code is as follows

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 of the
/// </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 // Otherwise, compress the file directly
            {
                // Open a compressed file
                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 of the
/// </summary>
public class UnZipFloClass
{
    public string unZipFile(string TargetFile, string fileDir)
    {
        string rootFile = " ";
        try
        {
            // Read a compressed file (zip file ) , ready to decompress
            ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
            ZipEntry theEntry;
            string path = fileDir;                  
            // The path to save the extracted file
            string rootDir = " ";                       
            // The first in the root directory 1 The name of the subfolder
            while ((theEntry = s.GetNextEntry()) != null)
            {
                rootDir = Path.GetDirectoryName(theEntry.Name);                         
                // Get the first in the root directory 1 The name of the class subfolder
                if (rootDir.IndexOf("\") >= 0)
                {
                    rootDir = rootDir.Substring(0, rootDir.IndexOf("\") + 1);
                }
                string dir = Path.GetDirectoryName(theEntry.Name);                   
                // The first in the root directory 1 Class is the name of the folder under the subfolder
                string fileName = Path.GetFileName(theEntry.Name);                   
                // The name of the file in the root directory
                if (dir != " " )                                                       
                    // Create a subfolder under the root directory , Unrestricted level
                {
                    if (!Directory.Exists(fileDir + "\" + dir))
                    {
                        path = fileDir + "\" + dir;                                               
                        // Creates a folder at the specified path
                        Directory.CreateDirectory(path);
                    }
                }
                else if (dir == " " && fileName != "")                                            
                    // Files in the root directory
                {
                    path = fileDir;
                    rootFile = fileName;
                }
                else if (dir != " " && fileName != "")                                            
                    // The first in the root directory 1 Class of the files in the subfolder
                {
                    if (dir.IndexOf("\") > 0)                                                           
                        // Specifies the path to save the file
                    {
                        path = fileDir + "\" + dir;
                    }
                }
                if (dir == rootDir)                                                                                 
                    // Determine if the file needs to be saved in the root directory
                {
                    path = fileDir + "\" + rootDir;
                }
                // The following is the decompression zip The basic steps of the file
                // The basic idea is to traverse all the files in the compressed file, create 1 It's the same file.
                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;
        }
    }  
}

Reference, create a new page, add two buttons, and add Click events for the buttons
The source code is as follows

protected void Button1_Click(object sender, EventArgs e)
{
        string[] FileProperties = new string[2];
        FileProperties[0] = "D:\unzipped\";// Directory of files to be compressed
        FileProperties[1] = "D:\zip\a.zip";  // The compressed object file
        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";// The file to be extracted
        FileProperties[1] = "D:\unzipped\";// Destination directory to be placed after unzipping
        UnZipFloClass UnZc = new UnZipFloClass();
        UnZc.unZipFile(FileProperties[0], FileProperties[1]);
}

I hope this article described to everyone asp.net program design is helpful.


Related articles: