.NET 下文件的压缩与解压

无论在发开.NET的Windows应用程序还是ASP.NET时,时常会碰到文件的压缩与解压,但是在微软的Framework 1.1中,并未提供相关的类库。这

里我们引用ICSharpCode,可以快速达到相关目的。该类库用C#开发,是开源的,感兴趣的朋友可以从这里下载

1.文件的压缩
将下载的 ICSharpCode.SharpZipLib.dll 添加到引用,新建一个 ZipClass 的类(ZipClass.cs)

using  System;
using  System.IO;

using  ICSharpCode.SharpZipLib.Zip;

namespace  JohnSolution.Common
{
    
/// <summary>
    
/// ZipClass 文件压缩类
    
/// </summary>

    public class ZipClass
    
{
        
public void StartZip()
        
{
            
// 要压缩的文件目录
            string[] filenames = Directory.GetFiles(@"e:/test");
                
            
// 生成的文件路径
            ZipOutputStream s = new ZipOutputStream(File.Create(@"e:/test.zip"));
        
            s.SetLevel(
5);
        
            
foreach (string file in filenames) 
            
{
                FileStream fs 
= File.OpenRead(file);
            
                
byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 
0, buffer.Length);
            
                ZipEntry entry 
= new ZipEntry(file);
                s.PutNextEntry(entry);
                s.Write(buffer, 
0, buffer.Length);
            
            }

        
            s.Finish();
            s.Close();

        }


    }

}


1.文件的解压
将下载的 ICSharpCode.SharpZipLib.dll 添加到引用,新建一个 UnZipClass 的类(UnZipClass.cs)

using  System;
using  System.IO;
using  System.Text;

using  ICSharpCode.SharpZipLib.Zip;

namespace  JohnSolution.Common
{
    
/// <summary>
    
/// UnZipClass 解压文件类
    
/// </summary>

    public class UnZipClass
    
{

        
public void StartUnZip()
        
{
            ZipInputStream s 
= new ZipInputStream(File.OpenRead(@"e:/test.zip"));

            ZipEntry entry;
            
while ((entry = s.GetNextEntry()) != null
            
{
                
int size = 2048;
                
byte[] buffer = new byte[2048];
                
                FileStream unZipFile 
= File.Create(@"e:/" + entry.Name);
                
while (true
                
{
                    size 
= s.Read(buffer, 0, buffer.Length);
                    
if (size > 0
                    
{
                        unZipFile.Write(buffer,
0,size);
                    }
 
                    
else 
                    
{
                        
break;
                    }

                }

                unZipFile.Flush();
                unZipFile.Close();
            }

            s.Close();

        }

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值