.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();

        }

    }

}

posted on 2005-05-16 12:14  ~~John 的网络涂鸦纪实~~  阅读(518)  评论(0编辑  收藏  举报

导航