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 target 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
{
/// <Summary>
/// Decompress the file
/// </Summary>
/// <Param name = "ARGs"> contains the file name to be extracted and the array of directory names to be extracted </param>
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
{
/// <Summary>
/// Compressed file
/// </Summary>
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
{< br> while (size {< br> int sizeread = streamtozip. read (buffer, 0, buffer. length);
zipstream. write (buffer, 0, sizeread);
size + = sizeread;
}< br> catch (system. exception ex)
{< br> throw ex;
}< br> 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
//---------------------------------------------
<% @ Page Language = "C #" codebehind = "webform1.aspx. cs" autoeventwireup = "false" inherits = "webzipunzip. webform1" %> & nbsp;
<Meta content = "Microsoft Visual Studio. NET 7.1" name = generator>
<Meta content = C # name = code_language>
<Meta content = JavaScript name = vs_defaultclientscript>
<Meta content = http://schemas.microsoft.com/intellisense/ie5 name = vs_targetschema>
<Form ID = form1 method = post runat = "server"> <? XML: namespace prefix = ASP/> <asp: button id = button1 style = "Z-INDEX: 101; left: 56px; position: absolute; top: 64px "runat =" server "text =" compression "> </ASP: button> <asp: button id = button2 style =" Z-INDEX: 102; left: Adjust PX; position: absolute; top: 64px "runat =" server "text =" Unzip "> </ASP: button> <input id = file1 style =" Z-INDEX: 103; left: 32px; position: absolute; top: 24px "type = file name = file1 runat =" server "> </form> </body>
//-------------------------------------------
// 5. 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>
/// Summary description for webform1.
/// </Summary>
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 );
}
/// <Summary>
/// Required method for designer support-do not modify
/// The contents of this method with the code editor.
/// </Summary>
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
}
}
OK! Try it.
This solution solves the problem of text in the file name and directory decompression.
There is no time to solve the problem of uploading and compressing the entire folder into a WinZip package in batches. If you have any solutions, share them.