您的位置:首页 > 其它

.NET 下文件的压缩与解压

2007-04-18 14:27 337 查看
无论在发开.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();




}


}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: