首页  编辑  

文件压缩和解压

Tags: /C#/文件目录操作/   Date Created:

using System . IO . Compression;

private void button1_Click( object sender , EventArgs e)

{

    FileStream vSourceFileStream = new FileStream ( @"c:\temp\temp.bmp" ,

        FileMode . Open, FileAccess . Read, FileShare . Read);

    FileStream vDestFileStream = new FileStream ( @"c:\temp\temp.zip" ,

        FileMode . OpenOrCreate, FileAccess . Write);

    GZipStream vGZipStream = new GZipStream (vDestFileStream,

        CompressionMode . Compress, true );

    byte [] vBuffer = new byte [ 0x1000 ];

    int vReadLength = vSourceFileStream . Read(vBuffer, 0 , vBuffer . Length);

    while (vReadLength > 0 )

   {

       vGZipStream . Write(vBuffer, 0 , vReadLength);

       vReadLength = vSourceFileStream . Read(vBuffer, 0 , vBuffer . Length);

   }

   vGZipStream . Close();

   vSourceFileStream . Close();

   vDestFileStream . Close();

}

private void button2_Click( object sender , EventArgs e)

{

    FileStream vSourceFileStream = new FileStream ( @"c:\temp\temp.zip" ,

        FileMode . Open, FileAccess . Read, FileShare . Read);

    FileStream vDestFileStream = new FileStream ( @"c:\temp\temp2.bmp" ,

        FileMode . OpenOrCreate, FileAccess . Write);

    GZipStream vGZipStream = new GZipStream (vSourceFileStream,

        CompressionMode . Decompress, true );

    byte [] vBuffer = new byte [ 0x1000 ];

    int vReadLength = vGZipStream . Read(vBuffer, 0 , vBuffer . Length);

    while (vReadLength > 0 )

   {

       vDestFileStream . Write(vBuffer, 0 , vReadLength);

       vReadLength = vGZipStream . Read(vBuffer, 0 , vBuffer . Length);

   }

   vGZipStream . Close();

   vSourceFileStream . Close();

   vDestFileStream . Close();

}