C#压缩单个zip格式文件

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

需要引用如下命名空间:

using System.IO;
using System.IO.Compression;

实现如下:

string sourceFile=@"C:\1.txt";
string destinationFile=@"D:\2.zip";
private const long BUFFER_SIZE = 20480;

if ( File.Exists ( sourceFile ))
{
    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 );

        // 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 ( );
    }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:C#显示友好时间格式的代码

下一篇:XML序列化反序列化C#示例代码