- using System.IO;
- using System.IO.Compression;
- string sourceFile=@"C:\\1.txt";
- string destinationFile=@"C:\\1.bin";
- private const long BUFFER_SIZE = 20480;
- if ( File.Exists ( sourceFile ))
- {
- FileStream sourceStream = null;
- FileStream destinationStream = null;
- DeflateStream compressedStream = null;
- try
- {
- // Read the bytes from the source file into a byte array
- sourceStream = new FileStream ( sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read );
- // 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 DeflateStream ( destinationStream, CompressionMode.Compress, true );
- long bufferSize = sourceStream.Length < BUFFER_SIZE ? sourceStream.Length : BUFFER_SIZE;
- byte[] buffer = new byte[bufferSize];
- int bytesRead = 0;
- long bytesWritten = 0;
- while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
- {
- compressedStream.Write(buffer, 0, bytesRead);
- bytesWritten += bufferSize;
- }
- }
- catch ( ApplicationException ex )
- {
- Console.WriteLine(ex.Message);
- }
- finally
- {
- // Make sure we allways close all streams
- if ( sourceStream != null )
- sourceStream.Close ( );
- if ( compressedStream != null )
- compressedStream.Close ( );
- if ( destinationStream != null )
- destinationStream.Close ( );
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2406201512916.html
来源: http://www.codesnippet.cn/detail/2406201512916.html