We often encounter the problem of batch upload and upload all files in a directory to the server. So how can we solve such problems? Previously, the technology generally used ActiveX and other methods. Here I use sharpzlib to implement it. I heard that vs2005 already has a compression and decompression solution, and I have no time to use vs2005, so we had to use vs2003 + sharpzlib to solve the problem.
1. Download the source code and sample code of version 0.84 sharpzlib from here.
2. After downloading it, you will find that it does not have the vs2003 solution file. It does not matter. You can create a zipunzip solution by yourself. Then, copy all the files and directories decompressed to the directory where your solution is located.
3. Click the show all files button in vs2003 solution Resource Manager (usually in the middle of the right), and then you can see many "virtual" icons, files, and folders, you can select them at a time and include them in the project.
4. Compile. It is best to use the release option. After compilation, you can see the zipunzip. dll class in \ bin \ release. If an error occurs during compilation, say assemblykeyfile or something like that, you can use a strong naming tool to create a new one or [Assembly: assemblykeyfile ("..... ")] Changed to [Assembly: assemblykeyfile (" ")] (this is not recommended ).
5. Create a webform project, add a reference to the zipunzip. dll class, and add the following files 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; // file to be decompressed
FileProperties [1] = zipFile. Substring (0, zipFile. LastIndexOf ("\") + 1); // the directory to be placed 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
{
///
/// Decompress the file
///
/// Contains the file name to be decompressed and the array of directory names to be decompressed
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 the extract directory
Directory. CreateDirectory (directoryName );
If (fileName! = String. Empty)
{
// Extract 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
{
///
/// Compressed file
///
Public class ZipClass
{
Public void ZipFile (string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize, string password)
{
// If the file is not found, an error is returned.
If (! System. IO. File. Exists (FileToZip ))
{
Throw new System. IO. FileNotFoundException ("The specified file" + FileToZip + "cocould 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 = 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 only to 9-means best compression
Foreach (string file in filenames)
{
// Open the 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 the crc, because the information
// About the size and crc shocould be stored in the header
// If it is not 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 that 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 call is required by the ASP. NET Web Form Designer.
//
InitializeComponent ();
Base. OnInit (e );
}
///
/// Required method for Designer support-do not modify
/// The contents of this method with the code editor.
///
Private void InitializeComponent ()
{
This. Button1.Click + = new System. EventHandler (this. button#click );
This. Button2.Click + = new System. EventHandler (this. Button2_Click );
This. Load + = new system. eventhandler (this. page_load );
}
# Endregion
# Region Compression
Private void button#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
// File to be compressed
Fileproperties [0] = fullname;
// Target file after compression
Fileproperties [1] = destpath + "\" + system. Io. Path. getfilenamewithoutextension (fullname) + ". Zip ";
Zipclass ZC = new zipclass ();
ZC. zipfilemain (fileproperties );
// Delete the file 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
// Decompress the file
// Attachmentunzip. upzip (fullname );
// String [] fileproperties = new string [2];
// Fileproperties [0] = fullname; // file to be decompressed
// Fileproperties [1] = system. Io. Path. getdirectoryname (fullname); // The target directory to be placed 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 text in the file name and directory decompression.