Asp. NET to tighten multiple files for a. zip file, to achieve the bulk download function

Source: Internet
Author: User
Tags compact datetime int size prev reset zip

Address http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

The following is an introduction to the solution of #ziplib under. Net.




1.bzip2


Participate in the ICSharpCode.SharpZipLib.dll reference, under the #develop installation catalog under the Sharpdevelopbin catalog. The using statement is then applied to the BZIP2





Class libraries are included in.


Austerity: The static method of applying BZIP2 compress.


Its first parameter is the input stream represented by the file to be tightened, and can be applied to the static method of System.IO.File OpenRead.


The second parameter is the output stream represented by the compact file to be built, which can be applied to the System.IO.File static method created, and the condensed filename is the filename of the file to be condensed.





Plus the tightening suffix. BZ (you can also take other file names).


The third parameter is the size of the block (typically 2048 integers) to be tightened.





Decompression: The static method of applying BZIP2 decompress.


Its first parameter is the input stream represented by the condensed file to be decompressed, and can be applied to the static method of System.IO.File OpenRead.


The second parameter is to build the output stream represented by the decompression file, you can apply System.IO.File static method create creation, because the file name of the extracted files is to remove the tightening





File extension name of the tightening file name (you can also be made to extract the file and the tightening file name).


Compile your testimonies, and then enter the bzip2 file name in the command line format (assuming that the built in C # file is bzip2, you can generate a condensed file; Enter the bzip2-d file name and unzip it.


Out of the file (-D is used for the implied decompression, you can also apply other symbols).


Oh, originally do austerity can be so simple, austerity results can also ah.

The code is as follows Copy Code
Using System;


Using System.IO;


Using ICSharpCode.SharpZipLib.BZip2;





Class MainClass


{


public static void Main (string[] args)


{


if (args[0] = = "-D") {//Decompression


Bzip2.decompress (File.openread (args[1]), File.create (Path.getfilenamewithoutextension (args[1)));


else {//tightening


Bzip2.compress (File.openread (args[0)), File.create (Args[0] + ". Bz"), 4096;


}


}


}


2.GZip
Participate in the ICSharpCode.SharpZipLib.dll reference, under the #develop installation catalog under the Sharpdevelopbin catalog. Then apply the using statement to the application to put the Gzip class

Libraries are included in.
Because Gzip has no BZip2 simple solution, is to only apply the flow method to solve the contraction. The specific approach is stated in the statutes.
compiler, and then enter the gzip file name in the command line format (assuming that the built in C # file is gzip, you can generate a condensed file; Enter gzip-d file name to extract the text

(-D is used for the implied decompression, you can also apply other symbols).

The code is as follows Copy Code
Using System;


Using System.IO;





Using ICSharpCode.SharpZipLib.GZip;





Class MainClass


{


public static void Main (string[] args)


{


if (args[0] = = "-D") {//Decompression


Stream s = new Gzipinputstream (File.openread (args[1));


Generates a Gzipinputstream stream to open the tightening file.


Because the Gzipinputstream is derived from the stream, it can be assigned to the stream.


The parameter of its function is a stream of files represented by a condensed file to decompress


FileStream fs = File.create (Path.getfilenamewithoutextension (args[1));


Generates a file stream that is used to generate an uncompressed file


You can use System.IO.File's static function create to generate a file stream


int size = 2048;//Specifies the size of the compact block, typically a multiple of 2048


byte[] WriteData = new byte[size];//Specifies the size of the buffer


while (true) {


Size = S.read (writedata, 0, size); Read a squeeze block


if (Size > 0) {


Fs. Write (writedata, 0, size);//writes the file stream represented by the decompression file


} else {


break;//If you read the end of the tightening file, stop


}


}


S.close ();


else {//tightening


Stream s = new Gzipoutputstream (File.create (args[0] + ". gz"));


Generates a gzipoutputstream stream that is used to generate a condensed file.


Because the Gzipoutputstream is derived from the stream, it can be assigned to the stream.


FileStream fs = File.openread (Args[0]);


/Generate a file stream, which is used to open the file to be tightened


You can use the System.IO.File static function OpenRead to generate a file stream


byte[] WriteData = new Byte[fs. Length];


Specifies the size of the buffer


Fs. Read (WriteData, 0, (int) fs. Length);


Read into file


S.write (writedata, 0, writedata.length);


Write to the austerity file


S.close ();


Closed file


}


}


}


The application of this class library is good, but also some shortcomings, it can only tighten the folder first level of the “ file ” (does not contain folders and subdirectories) of the scene, which can not meet my request, I want to be able to tighten the random path of multiple files.
No way, I had to think of another way. After a long time in someone else's article finally found inspiration, someone else's article is written in the Java implementation of the compact zip file, I looked at the invention in Java to achieve austerity in the zip file is easy. Brainwave I think of the j#,j# in. NET should have such a class in Java, and if so, I can refer to it in my C # application (spoofing. NET-specific speech interoperability). So I searched the contents of this area and finally found an example in MSDN.

(http://msdn.microsoft.com/en-gb/library/aa686114 (ZH-CN). Aspx#ehaa to get all the time AH), posted out to find the Code, Master Common window learning.

The code is as follows Copy Code

Using System;
Using System.Collections;
Using Java.util;
Using Java.util.zip;

Namespace Cszip
{
Public delegate enumeration Enumerationmethod ();

   ///<summary>
   ///wraps Java enumerators
   ///& LT;/SUMMARY>
    public class enumerationadapter:ienumerable
    {
        Private class Enumerationwrapper:ienumerator
         {
            private Enumerationmethod M_method;
            Private enumeration m_wrapped;
            Private object m_current;

Public Enumerationwrapper (Enumerationmethod method)
{
M_method = method;
}

IEnumerator
public Object Current
{
get {return m_current;}
}

public void Reset ()
{
m_wrapped = M_method ();
if (m_wrapped = null)
throw new InvalidOperationException ();
}

public bool MoveNext ()


{


if (m_wrapped = null)


Reset ();


BOOL result = M_wrapped.hasmoreelements ();


if (result)


M_current = M_wrapped.nextelement ();


return result;


}


}

Private Enumerationmethod M_method;

Public Enumerationadapter (Enumerationmethod method)
{
if (method = = null)
throw new ArgumentException ();
M_method = method;
}

IEnumerable
Public IEnumerator GetEnumerator ()
{
return new Enumerationwrapper (M_method);
}
}

Public delegate bool Filterentrymethod (ZipEntry e);

<summary>
Zip Stream Utils
</summary>
public class Ziputility
{
public static void CopyStream (Java.io.InputStream, Java.io.OutputStream to)
{
sbyte[] buffer = new sbyte[8192];
int got;
while (got =. Read (buffer, 0, buffer). Length)) > 0)
To.write (buffer, 0, got);
}

public static void Extractzipfile (ZipFile file, string path, Filterentrymethod filter)


{


foreach (ZipEntry entry in New Enumerationadapter (New Enumerationmethod (file.entries)))


{


if (!entry.isdirectory ())


{


if (filter = NULL | | Filter (entry)))


{


Java.io.InputStream s = file.getinputstream (entry);


Try


{


String fname = System.IO.Path.GetFileName (Entry.getname ());


String NewPath = System.IO.Path.Combine (Path, System.IO.Path.GetDirectoryName (Entry.getname ()));

System.IO.Directory.CreateDirectory (NewPath);

Java.io.FileOutputStream dest = new Java.io.FileOutputStream (System.IO.Path.Combine (NewPath, fname));


Try


{


CopyStream (S, dest);


}


Finally


{


Dest.close ();


}


}


Finally


{


S.close ();


}


}


}


}


}

<summary>
Create a new zip file
</summary>
<param name= "fileName" >zip file path </param>
Path to <returns>zip file </returns>
public static ZipFile Createemptyzipfile (String fileName)
{
New Zipoutputstream (FileName). Close ();
return new ZipFile (FileName);
}

&lt;summary&gt;


Add a file to the existing zip file for tightening


&lt;/summary&gt;


&lt;param name= "file" &gt;zip files &lt;/param&gt;


&lt;param name= "Filter" &gt;&lt;/param&gt;


&lt;param name= "Newfiles" &gt; The path of the file to be tightened &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public static ZipFile updatezipfile (ZipFile file, Filterentrymethod filter, string[] newfiles)


{


String prev = File.getname ();


string tmp = System.IO.Path.GetTempFileName ();


Zipoutputstream to = new Zipoutputstream (new Java.io.FileOutputStream (TMP));


Try


{


Copyentries (file, to, filter);


Add entries here


if (newfiles!= null)


{


foreach (string f in Newfiles)


{


ZipEntry z = new ZipEntry (f.remove (0, System.IO.Path.GetPathRoot (f). Length));


Z.setmethod (zipentry.deflated);


To.putnextentry (z);


Try


{


Java.io.FileInputStream s = new Java.io.FileInputStream (f);


Try


{


CopyStream (S, to);


}


Finally


{


S.close ();


}


}


Finally


{


To.closeentry ();


}


}


}


}


Finally


{


To.close ();


}


File.close ();

Now replace the old file with the new one
System.IO.File.Copy (TMP, Prev, true);
System.IO.File.Delete (TMP);

return new ZipFile (prev);
}

public static void Copyentries (ZipFile, Zipoutputstream to)
{
Copyentries (, to, NULL);
}

public static void Copyentries (ZipFile, Zipoutputstream to, Filterentrymethod filter)


{


foreach (ZipEntry entry in New Enumerationadapter) (new Enumerationmethod (. Entries))


{


if (filter = NULL | | Filter (Entry))


{


Java.io.InputStream s =. getInputStream (entry);


Try


{


To.putnextentry (entry);


Try


{


CopyStream (S, to);


}


Finally


{


To.closeentry ();


}


}


Finally


{


S.close ();


}


}


}


}


}


}

Application of foreign open source pressure solution Engross icsharpcode.sharpziplib to achieve pressure, the official website of the library for

Http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

Application Experience: You can follow the example to achieve simple compression decompression, you can pressure a folder in all the files, but there is no pressure subfolder of the declaration.
Some of the code on the Internet can not be compressed empty folder, and some pressurized with a RAR solution is not open, this is a point need to improve.
However, it is convenient to apply this library if you only need to press the image of &#8220; file &#8221; (without folders and subheadings) in the first level of the folder. and is the normal zip pattern.
The GZipStream class is stronger than the. NET supply in that it can adhere to a standard zip pattern to pressurize multiple files, while GZipStream does not have the option of pressuring multiple files, and needs to define itself,
This decompression is only the application of its own statutes can be, the universality is inferior to sharpziplib.

The code is as follows Copy Code

#region Pressure Decompression Method


&lt;summary&gt;


Features: Tightening files (temporarily only tighten files in the next level of folders, folders and their children are ignored)


&lt;/summary&gt;


&lt;param name= "Dirpath" &gt; tightened folder clip path &lt;/param&gt;


&lt;param name= "Zipfilepath" &gt; Generate the path of the austerity file, null defaults to the same level as the tightened folder, Name: folder name +.zip&lt;/param&gt;


&lt;param name= "Err" &gt; Slip information &lt;/param&gt;


&lt;returns&gt; whether to tighten success &lt;/returns&gt;


public bool ZipFile (string Dirpath, String Zipfilepath, out string err)


{


Err = "";


if (Dirpath = = string. Empty)


{


Err = "To tighten the folder cannot be empty!" ";


return false;


}


if (! Directory.Exists (Dirpath))


{


Err = "The folder to tighten does not exist!" ";


return false;


}


Apply folder name when tightening file name is empty +.zip


if (Zipfilepath = = string. Empty)


{


if (Dirpath.endswith ("\"))


{


Dirpath = dirpath.substring (0, dirpath.length-1);


}


Zipfilepath = Dirpath + ". zip";


}

Try


{


string[] filenames = Directory.GetFiles (Dirpath);


using (zipoutputstream s = new Zipoutputstream (File.create (Zipfilepath)))


{


S.setlevel (9);


byte[] buffer = new byte[4096];


foreach (string file in filenames)


{


ZipEntry entry = new ZipEntry (path.getfilename (file));


Entry. DateTime = DateTime.Now;


S.putnextentry (entry);


using (FileStream fs = File.openread (File))


{


int sourcebytes;


Todo


{


Sourcebytes = fs. Read (buffer, 0, buffer.) Length);


S.write (buffer, 0, sourcebytes);


while (sourcebytes &gt; 0);


}


}


S.finish ();


S.close ();


}


}


catch (Exception ex)


{


Err = ex. message;


return false;


}


return true;


}

&lt;summary&gt;


Function: Unzip the zip pattern file.


&lt;/summary&gt;


&lt;param name= "Zipfilepath" &gt; tightening file path &lt;/param&gt;


&lt;param name= "Unzipdir" &gt; Decompression file storage path, when the default and tightening files in the same level directory, with the tightening file folder with the same name &lt;/param&gt;


&lt;param name= "Err" &gt; Slip information &lt;/param&gt;


&lt;returns&gt; whether the decompression was successful &lt;/returns&gt;


public bool Unzipfile (string Zipfilepath, String unzipdir, out string err)


{


Err = "";


if (Zipfilepath = = string. Empty)


{


Err = "Compact file cannot be empty!" ";


return false;


}


if (! File.exists (Zipfilepath))


{


Err = "Crunch file does not exist!" ";


return false;


}


The folder with the same name as the compact file is the same as the compact file with the default folder


if (Unzipdir = = string. Empty)


Unzipdir = Zipfilepath.replace (Path.getfilename (Zipfilepath), Path.getfilenamewithoutextension (ZipFilePath));


if (!unzipdir.endswith ("\"))


Unzipdir + = "\";


if (! Directory.Exists (Unzipdir))


Directory.CreateDirectory (Unzipdir);

Try
{
using (zipinputstream s = new Zipinputstream (File.openread (Zipfilepath)))
{

ZipEntry Theentry;


while ((Theentry = S.getnextentry ())!= null)


{


String directoryname = Path.getdirectoryname (theentry.name);


String fileName = Path.getfilename (theentry.name);


if (Directoryname.length &gt; 0)


{


Directory.CreateDirectory (Unzipdir + directoryname);


}


if (!directoryname.endswith ("\"))


DirectoryName + = "\";


if (fileName!= String.Empty)


{


using (FileStream StreamWriter = file.create (Unzipdir + theentry.name))


{

int size = 2048;


byte[] data = new byte[2048];


while (true)


{


Size = s.read (data, 0, data.) Length);


if (Size &gt; 0)


{


StreamWriter.Write (data, 0, size);


}


Else


{


Break


}


}


}


}


}//while


}


}


catch (Exception ex)


{


Err = ex. message;


return false;


}


return true;


}//Decompression Stop


#endregion

You need to add a reference to SharpZipLib:

  code is as follows copy code

Using ICSharpCode.SharpZipLib.Zip;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.