Class compressed/decompressed with. NET 2.0)

Source: Internet
Author: User

The main function is to reduce the amount of data transmitted over the network,

Using System;
Using System. Collections. Generic;
Using System. Collections;
Using System. Text;
Using System. IO;
Using System. IO. Compression;

Namespace CompressionService
{
Public class Compression
{

// Compression
Public int Compress (byte [] source, ref byte [] dest)
{
Int resultcode;
Try
{
Memorystream MS = new memorystream ();

// Use the newly created memory stream for the compressed data.
Gzipstream compressedzipstream = new gzipstream (MS, compressionmode. Compress, true );

Compressedzipstream. Write (source, 0, source. Length );
Compressedzipstream. Close ();

Ms. Position = 0;
Dest = ms. ToArray ();

Ms. Close ();
Resultcode = 1;
}
Catch
{
Resultcode = 0;
}
Return resultcode;

}

// Extract

Public int UnCompress (byte [] source, ref byte [] dest)
{
Int resultcode;

Try
{
MemoryStream tempms = new MemoryStream (source );
Tempms. Position = 0;
GZipStream tempzip = new GZipStream (tempms, CompressionMode. Decompress );

Dest = GetDeData (tempzip, source );
Tempzip. Close ();
// Tempms. Close ();
// Console. WriteLine ("temporarily decoded data: {0}", System. Text. Encoding. Default. GetString (dest ));
Resultcode = 1;
}
Catch
{
Resultcode = 0;
}
Return resultcode;
}

Public byte [] GetDeData (Stream stream, byte [] temp) // obtain the decompressed file data
{

Int totalcount = 0;
Int datalen = temp. Length;
Int bytecount = datalen;

While (true)
{

Byte [] tempdata = new byte [bytecount];
Int bytesread = stream. Read (tempdata, 0, bytecount );
If (bytesread = 0)
Break;
Totalcount + = bytesread;
Bytecount = totalcount + bytesread;
}
Stream. Close ();

MemoryStream MS = new MemoryStream (temp );
GZipStream gs = new GZipStream (MS, CompressionMode. Decompress );
Byte [] alltempdata = new byte [totalcount];
Gs. Read (alltempdata, 0, alltempdata. Length );
Gs. Close ();
Return alltempdata;
}
}
}

The call class P is as follows:

Public static void Main ()
{
CompressionService. Compression ct = new CompressionService. Compression ();
Byte [] origialdata = OpenFile ();
Console. WriteLine ("Raw Data Length: {0}", origialdata. Length );
Byte [] test = NULL;
Ct. Compress (origialdata, ref test );
Console. writeline ("Compressed Data Length: {0}", test. Length );
Byte [] uncompressdata = NULL;
Ct. uncompress (test, ref uncompressdata );
Console. writeline ("decompress data: {0}, size: {1}", system. text. encoding. default. getstring (uncompressdata ). tostring (), uncompressdata. length );
}

Public static byte [] openfile ()
{
// String test = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzddafdsfsfsdafdfa, We are Chinese ";
Filestream infile = new filestream ("C: \ test.txt", filemode. Open, fileaccess. Read, fileshare. Read );
Byte [] buffer = new byte [infile. Length];
Infile. Read (buffer, 0, buffer. Length );

Console. writeline ("Raw data: {0}", system. Text. encoding. Default. getstring (buffer ));

// System. Text. encoding. ASCII. getstring (TEST ));
Return buffer;
}

 

For online File compression and decompression:

Public void CompressFile (string sourceFile, string destinationFile)
{
// Make sure the source file is there
If (File. Exists (sourceFile) = false)
Throw new FileNotFoundException ();

// Create the streams and byte arrays needed
Byte [] buffer = null;
Filestream sourcestream = NULL;
Filestream destinationstream = NULL;
Gzipstream compressedstream = NULL;

Try
{
// Read the bytes from the source file into a byte array
Sourcestream = new filestream (sourcefile, filemode. Open, fileaccess. Read, fileshare. Read );

// Read the source stream values into the buffer
Buffer = new byte [sourceStream. Length];
Int checkCounter = sourceStream. Read (buffer, 0, buffer. Length );

If (checkCounter! = Buffer. Length)
{
Throw new ApplicationException ();
}

// Open the filestream to write
Destinationstream = new filestream (destinationfile, filemode. openorcreate, fileaccess. Write );

// Create a compression stream pointing to the destiantion stream
Compressedstream = new gzipstream (destinationstream, compressionmode. Compress, true );

// Now write the compressed data to the destination file
CompressedStream. Write (buffer, 0, buffer. Length );
}
Catch (ApplicationException ex)
{
// MessageBox. Show (ex. Message, "An Error occurred when compressing the file:", MessageBoxButtons. OK, MessageBoxIcon. Error );
}
Finally
{
// Make sure we allways close all streams
If (sourcestream! = NULL)
Sourcestream. Close ();

If (compressedstream! = NULL)
Compressedstream. Close ();

If (destinationstream! = NULL)
DestinationStream. Close ();
}
}

Public void DecompressFile (string sourceFile, string destinationFile)
{
// Make sure the source file is there
If (File. Exists (sourceFile) = false)
Throw new FileNotFoundException ();

// Create the streams and byte arrays needed
Filestream sourcestream = NULL;
Filestream destinationstream = NULL;
Gzipstream decompressedstream = NULL;
Byte [] quartetbuffer = NULL;

Try
{
// Read in the compressed source stream
Sourcestream = new filestream (sourcefile, filemode. Open );

// Create a compression stream pointing to the destiantion stream
Decompressedstream = new gzipstream (sourcestream, compressionmode. decompress, true );

// Read the footer to determine the length of the destiantion File
Quartetbuffer = new byte [4];
Int position = (INT) sourcestream. Length-4;
SourceStream. Position = position;
SourceStream. Read (quartetBuffer, 0, 4 );
SourceStream. Position = 0;
Int checkLength = BitConverter. ToInt32 (quartetBuffer, 0 );

Byte [] buffer = new byte [checkLength + 100];

Int offset = 0;
Int total = 0;

// Read the compressed data into the buffer
While (true)
{
Int bytesRead = decompressedStream. Read (buffer, offset, 100 );

If (bytesRead = 0)
Break;

Offset + = bytesRead;
Total + = bytesRead;
}

// Now write everything to the destination file
DestinationStream = new FileStream (destinationFile, FileMode. Create );
DestinationStream. Write (buffer, 0, total );

// And flush everyhting to clean out the buffer
DestinationStream. Flush ();
}
Catch (ApplicationException ex)
{
// MessageBox. Show (ex. Message, "An Error occurred when extracting the file:", MessageBoxButtons. OK, MessageBoxIcon. Error );
}
Finally
{
// Make sure we allways close all streams
If (sourceStream! = Null)
SourceStream. Close ();

If (decompressedStream! = Null)
DecompressedStream. Close ();

If (destinationStream! = Null)
DestinationStream. Close ();
}

}

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.