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
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
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
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;
}