用.NET 2.0压缩/解压封装的类

告别WinRAR!用C#和SharpCompress库搞定RAR/ZIP/7Z压缩解压(附完整代码) 本文介绍了如何使用C#和SharpCompress库高效处理RAR、ZIP、7Z等多种压缩格式,无需依赖WinRAR等外部工具。通过详细的代码示例和实战指南,帮助.NET开发者快速实现压缩解压功能,提升开发效率。SharpCompress作为纯.NET解决方案,支持全格式操作,是替代传统压缩工具的优选方案。 阅读详情

主要功能是可以用来减轻网络数据的传输数据量,

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace CompressionService
{
    public class Compression
    {

//压缩
        public int Compress(byte[] source, ref byte[] dest)
        {
            int resultcode;
            try
            {
                MemoryStream ms = new MemoryStream();

                //Use the Newly Created Memory Stream for the Compressed Data.
                GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
    
                compressedzipStream.Write(source, 0, source.Length);
                compressedzipStream.Close();

                ms.Position = 0;
                dest = ms.ToArray();

                ms.Close();
                resultcode = 1;
            }
            catch
            {
                resultcode = 0;
            }
            return resultcode;

        }

//解压

public int UnCompress(byte[] source, ref byte[] dest)
        {
            int resultcode;   

          try
            {
                MemoryStream tempms = new MemoryStream(source);
                tempms.Position = 0;
                GZipStream tempzip = new GZipStream(tempms, CompressionMode.Decompress);

                dest = GetDeData(tempzip, source);
                tempzip.Close();
                //tempms.Close();
               // Console.WriteLine("临时解码数据:{0}", System.Text.Encoding.Default.GetString(dest));
                resultcode = 1;
            }
            catch
            {
                resultcode = 0;
            }
            return resultcode;
        }

        public byte[] GetDeData(Stream stream,byte[] temp) //取得解压后的文件数据
        {
           
            int totalcount = 0;
            int datalen = temp.Length;
            int bytecount = datalen;

            while (true)
            {
               
                byte[] tempdata = new byte[bytecount];
                int bytesread = stream.Read(tempdata, 0, bytecount);
                if (bytesread == 0)
                    break;              
                totalcount += bytesread;
                bytecount =totalcount+bytesread;
            }
            stream.Close();
                     
            MemoryStream ms = new MemoryStream(temp);
            GZipStream gs = new GZipStream(ms, CompressionMode.Decompress);
            byte[] alltempdata =new byte[totalcount];
            gs.Read(alltempdata, 0, alltempdata.Length);
            gs.Close();
            return alltempdata;
        }
    }
}

调用类P如下:

      public static void Main()
        {
           CompressionService.Compression ct = new CompressionService.Compression();
            byte[] origialdata = OpenFile();
            Console.WriteLine("原始数据长度:{0}", origialdata.Length);
            byte[] test = null;
            ct.Compress(origialdata, ref test);
            Console.WriteLine("压缩后数据长度:{0}", test.Length);
            byte[] uncompressdata = null;
            ct.UnCompress(test,ref uncompressdata);
            Console.WriteLine("解压数据:{0},大小为:{1}",System.Text.Encoding.Default.GetString(uncompressdata).ToString(),uncompressdata.Length);
    }

        public static byte[] OpenFile()
        {
            //string test = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzddafdsfsfsfsdafdfa,我们是中国人";
            FileStream infile = new FileStream("C://test.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] buffer = new byte[infile.Length];
            infile.Read(buffer, 0, buffer.Length);

            Console.WriteLine("原始数据:{0}", System.Text.Encoding.Default.GetString(buffer));

            // System.Text.Encoding.ASCII.GetString(test ));
            return buffer;
        } 

 

如果用来在线压缩和解压缩文件,如下:

    public void CompressFile (string sourceFile, string destinationFile )
       {
            // make sure the source file is there
            if ( File.Exists ( sourceFile ) == false )
                throw new FileNotFoundException ( );

            // Create the streams and byte arrays needed
            byte[] buffer = null;
            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 );

                // Read the source stream values into the buffer
                buffer = new byte[sourceStream.Length];
                int checkCounter = sourceStream.Read ( buffer, 0, buffer.Length );

                if ( checkCounter != buffer.Length )
                {
                    throw new ApplicationException ( );
                }

                // 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 GZipStream ( destinationStream, CompressionMode.Compress, true );

                // Now write the compressed data to the destination file
                compressedStream.Write ( buffer, 0, buffer.Length );
            }
            catch ( ApplicationException ex )
            {
               // MessageBox.Show ( ex.Message, "压缩文件时发生错误:", MessageBoxButtons.OK, MessageBoxIcon.Error );
            }
            finally
            {
                // Make sure we allways close all streams
                if ( sourceStream != null )
                    sourceStream.Close ( );

                if ( compressedStream != null )
                    compressedStream.Close ( );

                if ( destinationStream != null )
                    destinationStream.Close ( );
            }
        }

        public void DecompressFile ( string sourceFile, string destinationFile )
        {
            // make sure the source file is there
            if ( File.Exists ( sourceFile ) == false )
                throw new FileNotFoundException ( );

            // Create the streams and byte arrays needed
            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream decompressedStream = null;
            byte[] quartetBuffer = null;

            try
            {
                // Read in the compressed source stream
                sourceStream = new FileStream (sourceFile, FileMode.Open );

                // Create a compression stream pointing to the destiantion stream
                decompressedStream = new GZipStream (sourceStream, CompressionMode.Decompress, true );

                // Read the footer to determine the length of the destiantion file
                quartetBuffer = new byte[4];
                int position = (int)sourceStream.Length - 4;
                sourceStream.Position = position;
                sourceStream.Read (quartetBuffer, 0, 4 );
                sourceStream.Position = 0;
                int checkLength = BitConverter.ToInt32 ( quartetBuffer, 0 );

                byte[] buffer = new byte[checkLength + 100];

                int offset = 0;
                int total = 0;

                // Read the compressed data into the buffer
                while ( true )
               {
                    int bytesRead = decompressedStream.Read ( buffer, offset, 100 );

                    if ( bytesRead == 0 )
                        break;

                    offset += bytesRead;
                    total += bytesRead;
                }

                // Now write everything to the destination file
                destinationStream = new FileStream ( destinationFile, FileMode.Create );
                destinationStream.Write ( buffer, 0, total );

                // and flush everyhting to clean out the buffer
                destinationStream.Flush ( );
            }
            catch ( ApplicationException ex )
           {
                //MessageBox.Show(ex.Message, "解压文件时发生错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
           {
                // Make sure we allways close all streams
                if ( sourceStream != null )
                    sourceStream.Close ( );

                if ( decompressedStream != null )
                    decompressedStream.Close ( );

                if ( destinationStream != null )
                    destinationStream.Close ( );
            }

        }

在线压缩-解压功能实现:ASP.NET 2.0源代码揭秘 本文还有配套的精品资源,点击获取 简介:本文详细介绍了如何利用ASP.NET 2.0框架结合C#和Visual Studio 2005 IDE,实现一个在线文件压缩解压的Web应用程序。文章首先探讨了ASP.NET 2.0的基础特性,并深入解析了使用System.IO.Compression命名空间中的ZipFile来处理文件压缩解压的具体方法。作者提供了实现压缩和解... 阅读详情

相关推荐

C#实现文件压缩解压缩完整源码解析

压缩解压缩技术是现代计算机系统中不可或缺的数据处理手段。其核心目标是通过减少数据冗余、优化编码方式,从而降低数据存储空间并提升传输效率。压缩技术广泛应用于文件系统、网络协议、数据库备份、云存储等多个关键领域。从原理层面来看,压缩算法主要分为有损压缩与无损压缩两大。在软件系统中,尤其以无损压缩为主,例如DEFLATE、LZ77、Huffman编码等算法。它们通过识别数据中的重复模式或使用概率编码方式,将原始数据转换为更紧凑的形式。在实际应用中,压缩技术需在压缩比。

weixin_42126677的博客 1095

.NET 2.0压缩解压功能处理大型数据

摘要 如果你的应用程序从未使用过压缩,那么你很幸运。而对于另一部分使用压缩的开发人员来说,好消息是,.NET 2.0如今提供了两个来处理压缩解压问题。本文正是想讨论何时以及如何使用这些有用的工具。  引言  .NET框架2.0中的一个新名称空间是System.IO.Compression。这个新名称空间提供了两个数据压缩:DeflateStream和GZipStream。这两个压缩都支持无...

weixin_33704591的博客 211

C#使用DotNetZip实现ZIP文件解压缩完整源码与实战推荐

委托实现灵活过滤DotNetZip原生支持传入作为方法的参数,从而实现完全自定义的提取逻辑。// 超过100MB跳过// 使用方式逻辑分析:定义函数,返回布尔值决定是否提取;排除临时目录、超大文件及非日志型;调用批量执行带条件提取;第二个参数为搜索条件(此处为空,表示不限制);该机制极大提升了API的可编程性,使得复杂的业务规则可以直接编码实现。graph LRStart[开始筛选] --> Check1{是否为目录?

weixin_36001279的博客 1173

Asp.net 2.0 C#实现压缩/解压功能

Asp.net 2.0 C#实现压缩/解压功能 (示例代码下载)   (一). 实现功能     对文件及目录的压缩解压功能 (二). 运行图片示例   (三).代码    1. 压缩   1///    2/// 压缩   3///    4public class ZipClass   5{      6    public s

潘晓宇(panxiaoyu)的专栏 628

【转】用.NET 2.0压缩/解压封装

主要功能是可以用来减轻网络数据的传输数据量, using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.IO; using System.IO.Compression; namespace CompressionSer...

deform0032的博客 93

.NET 2.0压缩/解压封装 (转)

主要功能是可以用来减轻网络数据的传输数据量, using System;using System.Collections.Generic;using System.Collections;using System.Text;using System.IO;using System.IO.Compression; namespace CompressionService{ publ...

weixin_30905981的博客 95

ASP.NET在线压缩解压

以前做网站的时候经常要把网站的文件上传下载,有时遇到大型的网站会有几百甚至几千个文件,上传常常要上传好几个小时,当时就想能不能把所有文件打包上传然后再解压出来,但是在asp或者php的环境下几乎不可能(在服务器安装组件也可以实现,但一般的虚拟主机不可能给你装那些东西),后来在一个网站上看到了似的功能,可以实现在线压缩解压,然后上网搜了一下,发现有两种实现的方法。  一是rar压缩,这种方法一

szg3827的专栏 1036

NET 2.0-4.5 版本新特性

.NET 2.0-4.5 版本新特性 1 .NET 2.0 新特性—泛型 自定义定义泛型 class MyList<T> { private T[] arr; public MyList(int size) { arr = new T[size + 1]; } public ...

青石的博客 784

SevenZipSharp:强大的7-zip压缩解压缩库

SevenZipSharp:强大的7-zip压缩解压缩库 项目介绍 SevenZipSharp 是一个开源的 .NET 库,用于处理 7-zip 压缩解压缩操作。这个项目是基于原始的 CodePlex 项目的一个分支,经过多次迭代和改进,现在已经支持 .NET Standard 2.0.NET Framework 4.7.2 以及 .NET Core 3.1。它通过封装 7z.dll 或任何...

gitblog_00360的博客 1058

压缩/解压封装

//主要功能是可以用来减轻网络数据的传输数据量, using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.IO; using System.IO.Compression; namespace CompressionService {

老陈代码记录 355

压缩解压

核心库NewLife.Core内置了压缩相关功能扩展,并且独立实现的ZipFile还支持.NET2.0.NET4.0,该.NET4.5以后成为.NET Framework框架标配。数...

dotNET跨平台 415

.NET】利用SharpZipLib压缩解压文件夹中的所有文件、内存中动态压缩解压数据、内存中压缩解压文本

SharpZipLib是一个非常优秀的.NET环境下的ZIP文档压缩解压组件,免费且开源。 本篇文章介绍一下如何使用该组件压缩一个文件夹中的所有文件到ZIP文档、解压一个ZIP文档到文件夹,以及如何利用SharpZipLib在内存中动态的加解压数据。 下载最新版的SharpZipLib http://www.icsharpcode.net/OpenSource/SharpZipLib/Dow

binyao02123202的专栏 1338

.NET WebClient 下载部分文件会错误?可能是解压缩的锅

一直在使用 WebClient 下载文件,.NET 已经封装好,所以用起来代码非常简洁;但直到今天发现有一个文件一直不能正确下载下来。 本文介绍这个问题的原因和解决方法,更重要的是给出调查方法。 @TOC 本文所涉及到的域名已经过敏感信息处理,所以实际上你是无法访问到的;但这不影响本文对调查方法的描述。 问题 我原本是使用如下的代码去下载任意文件的(参数经过简化)。 private static...

walterlv - 吕毅 1188

C#实现文件夹压缩解压完整解决方案

文件压缩解压是现代软件开发中不可或缺的功能模块,广泛应用于数据传输、日志归档和资源打包等场景。C#依托.NET平台提供的命名空间,原生支持高性能的压缩操作,尤其对ZIP格式的深度集成使其成为行业主流选择。ZIP格式凭借其跨平台兼容性、良好的压缩比(基于Deflate算法)以及成熟的工具链生态,在性能与通用性之间实现了优秀平衡。相较于传统手动归档方式,C#通过流式处理机制实现自动化、低内存占用的压缩解压流程,显著提升开发效率与运行稳定性。本章为后续深入学习压缩API奠定理论基础。是。

weixin_30356433的博客 1209

ICSharpCode.SharpZipLib.dll:C#高效压缩解压库实战应用

ICSharpCode.SharpZipLib 最初由 IC#Code 团队为 .NET 平台开发,旨在填补早期 .NET Framework 在跨平台压缩处理上的空白。其设计遵循轻量、可扩展原则,支持 ZIP、GZIP、BZIP2、Tar 等主流格式,成为许多企业级应用日志归档、资源打包和系统备份的核心组件。

weixin_29069575的博客 1026

SharpZipLib: 功能强大的 .NET 库,用于压缩解压缩文件

SharpZipLib 是一个开源的 C# 库,它提供了对各种压缩算法的支持,包括 ZIP、GZIP 和 TAR。此库可用于在 .NET 平台上创建、读取和修改压缩文件。 ## 特点 - 支持多种压缩格式(ZIP、GZIP 和 TAR) - 高性能和可扩展性 - 全面支持 .NET Standard,可在多个平台上运行 - 易于使用的 API - 开源和免费 ## 应用场景 SharpZi

gitblog_00009的博客 1263
上一篇: .net下对注册表的各种操作
下一篇: ref 和 out 的使用区别
liusylon
博客等级 码龄23年 3粉丝 24原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值