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, "解压文件时发生错误:", 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 ( );
}
}
}
文章来源于领测软件测试网 https://www.ltesting.net/