In. net 1.1, we need to implement the compression function. Generally, we use the SharpZipLib of open source or call the J # class library.
Now the Compression function is added to. net 2.0, and The namespace is using System. IO. Compression;
The following is an example:
Compressed string
Copy codeThe Code is as follows:
Public static string ZipString (string unCompressedString)
{
Byte [] bytData = System. Text. Encoding. UTF8.GetBytes (unCompressedString );
MemoryStream MS = new MemoryStream ();
Stream s = new GZipStream (MS, CompressionMode. Compress );
S. Write (bytData, 0, bytData. Length );
S. Close ();
Byte [] compressedData = (byte []) ms. ToArray ();
Return System. Convert. ToBase64String (compressedData, 0, compressedData. Length );
}
Extract string
Copy codeThe Code is as follows:
Public static string UnzipString (string unCompressedString)
{
System. Text. StringBuilder uncompressedString = new System. Text. StringBuilder ();
Byte [] writeData = new byte [4096];
Byte [] bytData = System. Convert. FromBase64String (unCompressedString );
Int totalLength = 0;
Int size = 0;
Stream s = new GZipStream (new MemoryStream (bytData), CompressionMode. Decompress );
While (true)
{
Size = s. Read (writeData, 0, writeData. Length );
If (size> 0)
{
TotalLength + = size;
UncompressedString. Append (System. Text. Encoding. UTF8.GetString (writeData, 0, size ));
}
Else
{
Break;
}
}
S. Close ();
Return uncompressedString. ToString ();
}
Compressed file
Copy codeThe Code is as follows:
Public static bool AddZip (string srcFilename, string zipFileName)
{
If (! File. Exists (srcFilename ))
Return false;
Bool result;
FileStream fs = null, output = null;
GZipStream zipStream = null;
Try
{
Fs = new FileStream (srcFilename, FileMode. Open, FileAccess. Read );
Byte [] buffer = new byte [fs. Length];
Fs. Read (buffer, 0, buffer. Length );
Fs. Close ();
If (! File. Exists (zipFileName ))
{
Output = File. Create (zipFileName );
ZipStream = new GZipStream (output, CompressionMode. Compress );
ZipStream. Write (buffer, 0, buffer. Length );
Result = true;
}
Else
{
Result = false;
}
}
Catch (Exception)
{
Result = false;
}
Finally
{
If (zipStream! = Null)
{
ZipStream. Flush ();
ZipStream. Close ();
}
}
Return result;
}