Asp. NET to implement the online compression and decompression of files

Source: Internet
Author: User
Tags crc32 datetime empty header implement int size zip
asp.net| Compression | Online We often encounter problems with bulk uploads, and we also encounter problems uploading all the files from a directory to the server. So, how do you solve such problems? The previous technology generally used ActiveX, and so on, here I use sharpzlib to achieve, I heard that VS2005 has a compression and decompression solution, I have no time to use VS2005, so I had to use VS2003 + Sharpzlib to solve the problem.

1, first download from here 0.84 version of the Sharpzlib source code and sample code.

2, download down after you find it has no VS2003 solution file, no relationship. You can build on your own, create a new zipunzip solution first, and then copy all the files and directories that have been uncompressed above to the directory where your solution resides.

3, in the VS2003 Solution Explorer (usually in the middle right corner of the location) Click to show all the file buttons, and then you can see a lot of "virtual" icons, files and folders, you can select them, and then include in the project.

4, compile, best Use release option, after compiling completes you can see ZipUnzip.dll class in \bin\release\. If you compile the times wrong, say what AssemblyKeyFile and the like, you can use the strong naming tool to create a new one, you can also AssemblyInfo.cs [Assembly:assemblykeyfile ("... ")] to: [Assembly:assemblykeyfile (" ")] (not recommended).

5. Create a new WebForm project, add a reference to the ZipUnzip.dll class, and add the following file and content:

// ------------------------------------------
1. AttachmentUnZip.cs
// ------------------------------------------
Using System;
Using System.IO;
Using ICSharpCode.SharpZipLib.Zip;
Using ICSharpCode.SharpZipLib.GZip;
Using ICSharpCode.SharpZipLib.BZip2;
Using ICSharpCode.SharpZipLib.Checksums;
Using ICSharpCode.SharpZipLib.Zip.Compression;
Using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

Namespace Webzipunzip
{
public class Attachmentunzip
{
Public Attachmentunzip ()
{}
public static void Upzip (String zipfile)
{
string []fileproperties=new string[2];
fileproperties[0]=zipfile;//files to be extracted
Fileproperties[1]=zipfile.substring (0,zipfile.lastindexof ("\") +1)//The target directory after decompression
Unzipclass unzc=new Unzipclass ();
Unzc.unzip (fileproperties);
}
}
}

// ---------------------------------------------
2. UnZipClass.cs
// ---------------------------------------------

Using System;
Using System.IO;
Using ICSharpCode.SharpZipLib.Zip;
Using ICSharpCode.SharpZipLib.GZip;
Using ICSharpCode.SharpZipLib.BZip2;
Using ICSharpCode.SharpZipLib.Checksums;
Using ICSharpCode.SharpZipLib.Zip.Compression;
Using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

Namespace Webzipunzip
{
public class Unzipclass
{
///
Extract Files
///
Contains the filename to extract and the directory to extract to array group
public void UnZip (string[] args)
{
Zipinputstream s = new Zipinputstream (File.openread (args[0));
Try
{
ZipEntry Theentry;
while ((Theentry = S.getnextentry ())!= null)
{
String directoryname = Path.getdirectoryname (args[1]);
String fileName = Path.getfilename (theentry.name);

Generate Unzip Directory
Directory.CreateDirectory (directoryname);

if (fileName!= String.Empty)
{
Unzip the file to the specified directory
FileStream StreamWriter = file.create (args[1]+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 ();
}
catch (Exception EU)
{
Throw EU;
}
Finally
{
S.close ();
}
}//end UnZip

public static bool Unzipfile (string file, String dir)
{
Try
{
if (! Directory.Exists (dir))
Directory.CreateDirectory (dir);
String filefullname = Path.Combine (dir,file);
Zipinputstream s = new Zipinputstream (File.openread (filefullname));
 
ZipEntry Theentry;
while ((Theentry = S.getnextentry ())!= null)
{
String directoryname = Path.getdirectoryname (theentry.name);
String fileName = Path.getfilename (theentry.name);
 
if (directoryname!= String.Empty)
Directory.CreateDirectory (Path.Combine (dir, directoryname));
if (fileName!= String.Empty)
{
FileStream StreamWriter = file.create (Path.Combine (dir,theentry.name));
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 true;
}
catch (Exception)
{
Throw
}
}
}//end Unzipclass
}

// ----------------------------------------------
3. ZipClass.cs
// ----------------------------------------------
Using System;
Using System.IO;
Using ICSharpCode.SharpZipLib.Zip;
Using ICSharpCode.SharpZipLib.GZip;
Using ICSharpCode.SharpZipLib.BZip2;
Using ICSharpCode.SharpZipLib.Checksums;
Using ICSharpCode.SharpZipLib.Zip.Compression;
Using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

Namespace Webzipunzip
{
///
Compress files
///
public class Zipclass
{
public void ZipFile (string filetozip, string zipedfile, int compressionlevel, int blocksize,string password)
{
If the file is not found, the error
if (! System.IO.File.Exists (Filetozip))
{
throw new System.IO.FileNotFoundException ("The specified file" + Filetozip + "could not be found. Zipping Aborderd ");
}

System.IO.FileStream streamtozip = new System.IO.FileStream (Filetozip,system.io.filemode.open, System.IO.FileAccess.Read);
System.IO.FileStream ZipFile = System.IO.File.Create (zipedfile);
Zipoutputstream ZIPstream = new Zipoutputstream (ZipFile);
ZipEntry zipentry = new ZipEntry ("Zippedfile");
Zipstream.putnextentry (ZipEntry);
Zipstream.setlevel (CompressionLevel);
byte[] buffer = new Byte[blocksize];
System.Int32 size =streamtozip.read (buffer,0,buffer. Length);
Zipstream.write (buffer,0,size);
Try
{
while (Size < streamtozip.length)
{
int Sizeread =streamtozip.read (buffer,0,buffer. Length);
Zipstream.write (Buffer,0,sizeread);
Size + = Sizeread;
}
}
catch (System.Exception ex)
{
Throw ex;
}
Zipstream.finish ();
Zipstream.close ();
Streamtozip.close ();
}

public void Zipfilemain (string[] args)
{
string[] filenames = Directory.GetFiles (args[0));
string[] filenames = new String[]{args[0]};
 
Crc32 CRC = New Crc32 ();
Zipoutputstream s = new Zipoutputstream (File.create (args[1));

S.setlevel (6); 0-store to 9-means best compression

foreach (string file in filenames)
{
Open compressed file
FileStream fs = File.openread (File);
byte[] buffer = new BYTE[FS. Length];
Fs. Read (buffer, 0, buffer.) Length);
ZipEntry entry = new ZipEntry (file);

Entry. DateTime = DateTime.Now;

Set Size and CRC, because the information
About the size and CRC should is stored in the header
If it is isn't set it is automatically written in the footer.
(in this case size = = CRC = 1 in the header)
Some zip programs have problems with ZIP files, don ' t store
The size and CRC in the header.
Entry. Size = fs. Length;
Fs. Close ();

Crc. Reset ();
Crc. Update (buffer);

Entry. CRC = CRC. Value;

S.putnextentry (entry);

S.write (buffer, 0, buffer. Length);

}
S.finish ();
S.close ();
}
}
}

// ---------------------------------------------
4.webform1.aspx.cs
//-------------------------------------------

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.IO;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;

Namespace Webzipunzip
{
///
Summary description for WebForm1.
///
public class WebForm1:System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
protected System.Web.UI.WebControls.Button Button2;

private void Page_Load (object sender, System.EventArgs e)
{
Put user code to initialize the page here
}

#region Web Form Designer generated code
Override protected void OnInit (EventArgs e)
{
//
Codegen:this the call are required by the ASP.net Web Form Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

///
Required to Designer support-do not modify
The contents is with the Code Editor.
///
private void InitializeComponent ()
{
This. Button1.Click + = new System.EventHandler (this. Button1_Click);
This. Button2.click + = new System.EventHandler (this. button2_click);
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion

#region Compression
private void Button1_Click (object sender, System.EventArgs e)
{
string []fileproperties=new string[2];
String Fullname=this. File1.postedfile.filename;//c:\test\a.txt
String Destpath=system.io.path.getdirectoryname (fullName);//c:\test
Files to be compressed
Fileproperties[0]=fullname;

Compressed destination file
fileproperties[1]= destpath + "\" + System.IO.Path.GetFileNameWithoutExtension (fullName) + ". zip";
Zipclass zc=new Zipclass ();
Zc.zipfilemain (fileproperties);

Delete files before compression
System.IO.File.Delete (FullName);
}

#endregion

#region Decompression
private void Button2_Click (object sender, System.EventArgs e)
{
String Fullname=this. File1.postedfile.filename;//c:\test\a.zip
Extract Files
Attachmentunzip.upzip (FullName);

string[] fileproperties = new string[2];
Fileproperties[0] = fullname;//files to be extracted
FILEPROPERTIES[1] = System.IO.Path.GetDirectoryName (fullName);//The target directory after decompression
Unzipclass unzc=new Unzipclass ();
Unzc.unzip (fileproperties);
String dir = System.IO.Path.GetDirectoryName (fullName);
String fileName = System.IO.Path.GetFileName (fullName);
Unzipclass.unzipfile (FileName, dir);
}
#endregion
}
}
This solution solves the problem of the text in the filename, and the problem of directory decompression.

As for the whole folder bulk upload and compressed into a WinZip compression package problem, no time to solve, if you have a solution, may wish to share.

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.