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
{
/// <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
{
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
//---------------------------------------------
<% @ Page language = "c #" Codebehind = "WebForm1.aspx. cs" AutoEventWireup = "false" Inherits = "WebZipUnzip. WebForm1" %>
<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> </HTML>
//-------------------------------------------
// 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.