C#实现文件的压缩和解压缩

在C#中实现文件的压缩和解压缩,需要使用第三方的组建完成。常用的是:SharpZipLib组建。

下载地址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

1、压缩和解压缩有两种典型的算法,一种是BZIP2算法,另一种是GZIP算法。BZIP2能够获得较高的压缩比,但是压缩和解压缩比较耗时,GZIP效率比较高,但是压缩比较低。

2、BZIP2压缩算法的相关类,位于命名空间:ICSharpCode.SharpZipLib.BZip2中,算法要求指定输入流和输出流,并指定压缩方法使用的块大小,一般为2048.

3、GZIP压缩算法的相关类,位于命名空间:ICSharpCode.SharpZipLib.GZip中,首先创建GZipOutputStream类实例,作为压缩文件的输出流,使用GZipOutputStream类实例的Write方法,将从源文件读取的数据写入输入流。同时完成压缩运算。

4、使用实例:

 

class ZipAndUnzipFile
    {
        public static void GetZipAndUnzipFile(){

            string srcFile = @"..\..\testzip.txt";//准备压缩的文件路径
            string zipFile = @"..\..\testzip";//压缩后的文件路径
            string unzipFile = @"..\..\testzip_unzip.txt";//解压后的文件路径
            Console.WriteLine("使用BZIP开始压缩文件……");
            if (BZipFile(srcFile, zipFile + ".bz"))//使用BZIP压缩文件
            {
                Console.WriteLine("文件压缩完成");
            }
            else
            {
                Console.WriteLine("文件压缩失败");
            }
            Console.WriteLine("使用BZIP开始解压文件……");
            if (UnBzipFile(zipFile + ".bz", unzipFile))//使用BZIP解压文件
            {
                Console.WriteLine("文件解压完成");
            }
            else
            {
                Console.WriteLine("文件解压失败");
            }
            Console.WriteLine("使用GZIP开始压缩文件……");
            if (GZipFile(srcFile, zipFile + ".gz"))//使用GZIP压缩文件
            {
                Console.WriteLine("文件压缩完成");
            }
            else
            {
                Console.WriteLine("文件压缩失败");
            }
            Console.WriteLine("使用GZIP开始解压文件……");
            if (UnGzipFile(zipFile + ".gz", unzipFile))//使用GZIP解压文件
            {
                Console.WriteLine("文件解压完成");
            }
            else
            {
                Console.WriteLine("文件解压失败");
            }
            Console.ReadLine();
        }
    //使用BZIP压缩文件的方法
        static bool BZipFile(string sourcefilename, string zipfilename)
        {
            bool blResult;//表示压缩是否成功的返回结果
            //为源文件创建文件流实例,作为压缩方法的输入流参数
            FileStream srcFile = File.OpenRead(sourcefilename);
            //为压缩文件创建文件流实例,作为压缩方法的输出流参数
            FileStream zipFile = File.Open(zipfilename, FileMode.Create);
            try
            {
                //以4096字节作为一个块的方式压缩文件
                BZip2.Compress(srcFile, zipFile, 4096);
                blResult=true;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult=false;
            }
            srcFile.Close();//关闭源文件流
            zipFile.Close();//关闭压缩文件流
            return blResult;
        }
        //使用BZIP解压文件的方法
        static bool UnBzipFile(string zipfilename,string unzipfilename)
        {
            bool blResult;//表示解压是否成功的返回结果
            //为压缩文件创建文件流实例,作为解压方法的输入流参数
            FileStream zipFile = File.OpenRead(zipfilename);
            //为目标文件创建文件流实例,作为解压方法的输出流参数
            FileStream destFile = File.Open(unzipfilename, FileMode.Create);
            try
            {
                BZip2.Decompress(zipFile, destFile);//解压文件
                blResult=true;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult=false;
            }
            destFile.Close();//关闭目标文件流
            zipFile.Close();//关闭压缩文件流
            return blResult;
        }
        //使用GZIP压缩文件的方法
        static bool GZipFile(string sourcefilename, string zipfilename)
        {
            bool blResult;//表示压缩是否成功的返回结果
            //为源文件创建读取文件的流实例
            FileStream srcFile = File.OpenRead(sourcefilename);
            //为压缩文件创建写入文件的流实例,
            GZipOutputStream zipFile = new GZipOutputStream(File.Open(zipfilename,FileMode.Create));
            try
            {
                byte[] FileData = new byte[srcFile.Length];//创建缓冲数据
                srcFile.Read(FileData, 0, (int)srcFile.Length);//读取源文件
                zipFile.Write(FileData, 0, FileData.Length);//写入压缩文件
                blResult = true;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult = false;
            }
            srcFile.Close();//关闭源文件
            zipFile.Close();//关闭压缩文件
            return blResult;
        }
        //使用GZIP解压文件的方法
        static bool UnGzipFile(string zipfilename, string unzipfilename)
        {
            bool blResult;//表示解压是否成功的返回结果
            //创建压缩文件的输入流实例
            GZipInputStream zipFile = new GZipInputStream(File.OpenRead(zipfilename));
            //创建目标文件的流
            FileStream destFile = File.Open(unzipfilename, FileMode.Create);
            try
            {
                int buffersize = 2048;//缓冲区的尺寸,一般是2048的倍数
                byte[] FileData = new byte[buffersize];//创建缓冲数据
                while(buffersize>0)//一直读取到文件末尾
                {
                    buffersize = zipFile.Read(FileData,0,buffersize);//读取压缩文件数据
                    destFile.Write(FileData,0,buffersize);//写入目标文件
                }
                blResult = true;
            }
            catch(Exception ee)
            {
                Console.WriteLine(ee.Message);
                blResult = false;
            }
            destFile.Close();//关闭目标文件
            zipFile.Close();//关闭压缩文件
            return blResult;
        }
    }

转载于:https://www.cnblogs.com/zxl/archive/2008/10/11/1308693.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于大文件的流式压缩加解密,可以使用C#中的GZipStream和CryptoStream类来实现。 首先,我们需要使用GZipStream类对文件进行压缩,代码如下: ```csharp using System.IO; using System.IO.Compression; // 压缩文件 public static void CompressFile(string sourceFilePath, string compressedFilePath) { using (FileStream sourceFile = new FileStream(sourceFilePath, FileMode.Open)) { using (FileStream compressedFile = File.Create(compressedFilePath)) { using (GZipStream compressionStream = new GZipStream(compressedFile, CompressionMode.Compress)) { // 使用GZipStream类对文件进行压缩 sourceFile.CopyTo(compressionStream); } } } } ``` 接着,我们可以使用CryptoStream类对压缩后的文件进行加密,代码如下: ```csharp using System.Security.Cryptography; // 加密文件 public static void EncryptFile(string sourceFilePath, string encryptedFilePath, byte[] key, byte[] iv) { using (FileStream sourceFile = new FileStream(sourceFilePath, FileMode.Open)) { using (FileStream encryptedFile = File.Create(encryptedFilePath)) { using (GZipStream compressionStream = new GZipStream(encryptedFile, CompressionMode.Compress)) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; using (CryptoStream encryptionStream = new CryptoStream(compressionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { // 使用CryptoStream类对压缩后的文件进行加密 sourceFile.CopyTo(encryptionStream); } } } } } } ``` 其中,key和iv分别为加密所需要的密钥和初始化向量,可以自行生成或者由用户输入。 最后,我们可以使用相同的过程对加密后的文件进行解密和解压缩,代码如下: ```csharp // 解密文件 public static void DecryptFile(string encryptedFilePath, string decryptedFilePath, byte[] key, byte[] iv) { using (FileStream encryptedFile = new FileStream(encryptedFilePath, FileMode.Open)) { using (FileStream decryptedFile = File.Create(decryptedFilePath)) { using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; using (CryptoStream decryptionStream = new CryptoStream(encryptedFile, aes.CreateDecryptor(), CryptoStreamMode.Read)) { using (GZipStream decompressionStream = new GZipStream(decryptionStream, CompressionMode.Decompress)) { // 解密和解压缩文件 decompressionStream.CopyTo(decryptedFile); } } } } } } ``` 需要注意的是,解密和解压缩的顺序应该和加密和压缩的顺序相反。同时,密钥和初始化向量应该与加密时使用的一致。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值