[C#] C#压缩单个zip格式文件 →→→→→进入此内容的聊天室

来自 , 2019-09-15, 写在 C#, 查看 121 次.
URL http://www.code666.cn/view/34609bdc
  1. using System.IO;
  2. using System.IO.Compression;
  3. string sourceFile=@"C:\1.txt";
  4. string destinationFile=@"D:\2.zip";
  5.         private const long BUFFER_SIZE = 20480;
  6.        if ( File.Exists ( sourceFile ))
  7.        {
  8.             FileStream sourceStream = null;
  9.             FileStream destinationStream = null;
  10.             GZipStream compressedStream = null;
  11.             try
  12.             {
  13.                 // Read the bytes from the source file into a byte array
  14.                 sourceStream = new FileStream ( sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read );
  15.  
  16.                 // Open the FileStream to write to
  17.                 destinationStream = new FileStream ( destinationFile, FileMode.OpenOrCreate, FileAccess.Write );
  18.  
  19.                 // Create a compression stream pointing to the destiantion stream
  20.                 compressedStream = new DeflateStream ( destinationStream, CompressionMode.Compress, true );
  21.             long bufferSize = sourceStream.Length < BUFFER_SIZE ? sourceStream.Length : BUFFER_SIZE;  
  22.             byte[] buffer = new byte[bufferSize];  
  23.             int bytesRead = 0;  
  24.             long bytesWritten = 0;  
  25.             while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) != 0)  
  26.             {  
  27.                 compressedStream.Write(buffer, 0, bytesRead);  
  28.                 bytesWritten += bufferSize;  
  29.             }  
  30.  
  31.             }
  32.             catch ( ApplicationException ex )
  33.             {
  34.                 Console.WriteLine(ex.Message);
  35.             }
  36.             finally
  37.             {
  38.                 // Make sure we allways close all streams
  39.                 if ( sourceStream != null )
  40.                     sourceStream.Close ( );
  41.  
  42.                 if ( compressedStream != null )
  43.                     compressedStream.Close ( );
  44.  
  45.                 if ( destinationStream != null )
  46.                     destinationStream.Close ( );
  47.             }
  48.         }
  49. //csharp/1112

回复 "C#压缩单个zip格式文件"

这儿你可以回复上面这条便签

captcha