asp.net C # Compression Packaging file Example

Source: Internet
Author: User
Tags crc32 datetime int size relative zip

<summary>
Compress and Decompress files
</summary>
public class Zipclass
{
<summary>
All file Caches
</summary>
list<string> files = new list<string> ();

<summary>
All Empty directory Caches
</summary>
list<string> paths = new list<string> ();

   ///<summary>
   ///Compress a single file
   ///</summary
   ///<param name= "Filetozip" > Files to compress </param>
   ///< param name= "Zipedfile" > Compressed file Full name </param>
   ///<param name= "CompressionLevel" > Compression degree, range 0-9, the larger the number, the higher the compression program </param>
   ///<param name= "blockSize" > chunking size </param>
    public void ZipFile (string filetozip, string zipedfile, int compressionlevel, int blockSize)
& nbsp;   {
        if (! System.IO.File.Exists (Filetozip)//If the file is not found, the error
        {
             throw new FileNotFoundException ("The specified file" + Filetozip + "could not to be found." Zipping Aborderd ");
       }

FileStream streamtozip = new FileStream (Filetozip, FileMode.Open, FileAccess.Read);
FileStream ZipFile = file.create (zipedfile);
Zipoutputstream ZIPstream = new Zipoutputstream (ZipFile);
ZipEntry zipentry = new ZipEntry (filetozip);
Zipstream.putnextentry (ZipEntry);
Zipstream.setlevel (CompressionLevel);
byte[] buffer = new Byte[blocksize];
int 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 (Exception ex)
{
Gc. Collect ();
Throw ex;
}

Zipstream.finish ();
Zipstream.close ();
Streamtozip.close ();
Gc. Collect ();
}

<summary>
Compressed directory (including subdirectories and all files)
</summary>
<param name= "RootPath" > root directory to compress </param>
<param name= "DestinationPath" > Save path </param>
<param name= "Compresslevel" > Compression degree, Range 0-9, the larger the number, the higher the compression program </param>
public void Zipfilefromdirectory (string rootpath, string destinationpath, int compresslevel)
{
GetAllDirectories (RootPath);

/* while (Rootpath.lastindexof ("\") + 1 = rootpath.length)//Check whether the path ends with "\"
{

RootPath = rootpath.substring (0, rootpath.length-1);//If yes, remove the end of "\"

}
*/
String rootmark = rootpath.substring (0, Rootpath.lastindexof ("\") + 1);//Get the position of the current path to convert the compressed content to a relative path for compression.
String Rootmark = RootPath + "\ \";//Get the position of the current path to convert the compressed content to a relative path for compression.
Crc32 CRC = New Crc32 ();
Zipoutputstream outputstream = new Zipoutputstream (File.create (DestinationPath));
Outputstream.setlevel (Compresslevel); 0-store to 9-means best compression
foreach (string file in files)
{
FileStream FileStream = file.openread (file);//Open Compressed file
byte[] buffer = new Byte[filestream.length];
FileStream.Read (buffer, 0, buffer. Length);
ZipEntry entry = new ZipEntry (file. Replace (Rootmark, String. Empty));
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 = Filestream.length;
Filestream.close ();
Crc. Reset ();
Crc. Update (buffer);
Entry. CRC = CRC. Value;
Outputstream.putnextentry (entry);
Outputstream.write (buffer, 0, buffer. Length);
}

This.files.Clear ();

foreach (String emptypath in Paths)
{
ZipEntry entry = new ZipEntry (Emptypath.replace (Rootmark, String. Empty) + "/");
Outputstream.putnextentry (entry);
}

This.paths.Clear ();
Outputstream.finish ();
Outputstream.close ();
Gc. Collect ();
}

<summary>
Obtain all files and folders under the catalogue, respectively, into files and paths
</summary>
<param name= "RootPath" > root directory </param>
private void GetAllDirectories (string rootpath)
{
string[] subpaths = directory.getdirectories (RootPath);//Get all subdirectories
foreach (string path in subpaths)
{
GetAllDirectories (path); Do the same thing as the root directory for each word directory: Locate the subdirectory and save the file name of the current directory in the list
}
string[] files = directory.getfiles (RootPath);
foreach (string file in files)
{
THIS.FILES.ADD (file)//Save all file names in current directory to file list
}
if (subpaths.length = = files. Length && files. Length = = 0)//If an empty directory
{
THIS.PATHS.ADD (RootPath);//Record Empty directory
}
}

   ///<summary>
   ///uncompressed files (containing subdirectories in compressed files)
   ///< /summary>
   ///<param name= "Zipfilepath" > the file path to be uncompressed </param>
    ///<param name= "Unzippath" > uncompressed to the specified directory </param>
   ///<returns> extracted files list </returns>
    public list<string> UnZip (string zipfilepath, string unzippath)
    {
       //extracted file list
         list<string> unzipfiles = new list<string> ();

Check whether the output directory ends with "\"
if (Unzippath. EndsWith ("\") = = False | | Unzippath. EndsWith (": \") = = False)
{
Unzippath + = "\";
}

Zipinputstream s = new Zipinputstream (File.openread (Zipfilepath));
ZipEntry Theentry;
while ((Theentry = S.getnextentry ())!= null)
{
String directoryname = Path.getdirectoryname (Unzippath);
String fileName = Path.getfilename (theentry.name);

Generate extract Directory "user uncompressed to hard disk root directory, do not need to create"
if (!string. IsNullOrEmpty (directoryname))
{
Directory.CreateDirectory (directoryname);
}

if (fileName!= String.Empty)
{
If the file is compressed to a size of 0 then the file is empty, so no read write is required
if (theentry.compressedsize = 0)
Break
Unzip the file to the specified directory
DirectoryName = Path.getdirectoryname (Unzippath + theentry.name);
Create the following directories and subdirectories
Directory.CreateDirectory (directoryname);

Record exported files
Unzipfiles.add (Unzippath + theentry.name);

FileStream StreamWriter = file.create (Unzippath + 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 ();
Gc. Collect ();
return unzipfiles;
}
}

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.