本文实例讲述了asp.net C#实现解压缩文件的方法。一共给大家介绍了三段代码,一个是简单的解压缩单个zip文件,后一个可以解压批量的大量的但需要调用ICSharpCode.SharpZipLib.dll类了,最后一个比较实例可压缩也可以解压缩了分享给大家供大家参考。具体如下:
解压缩单个文件:
复制代码 代码如下:
using System.IO;
using System.IO.Compression;
string sourceFile=@"D:2.zip";
string destinationFile=@"D:1.txt";
private const long BUFFER_SIZE = 20480;
// make sure the source file is there
if (File.Exists ( sourceFile ))
{
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 DeflateStream ( 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 )
{
Console.WriteLine(ex.Message, "解压文件时发生错误:");
}
finally
{
// Make sure we allways close all streams
if ( sourceStream != null )
sourceStream.Close ( );
if ( decompressedStream != null )
decompressedStream.Close ( );
if ( destinationStream != null )
destinationStream.Close ( );
}
}
批量解压缩(这需要调用一个解压缩类库。。 ICSharpCode.SharpZipLib.dll)
复制代码 代码如下: