日期:2014-05-20  浏览次数:20827 次

如何用C#实现压缩,压缩格式为ZIP(可商用)。
如题。。需要源代码。。

------解决方案--------------------
System.IO.Compression 命名空间
.net2.0
------解决方案--------------------
请参考我的blog,有完整源码
http://blog.csdn.net/BlueDog/archive/2006/12/29/1466527.aspx
------解决方案--------------------
http://www.w3sky.com/2/2505.html
------解决方案--------------------
class clsZip
{
//原作:downmoon
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 to
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, "压缩文件时发生错误: ", 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 );