如何使用C#压缩文件及注意的问题!
2024-07-21 02:19:06
供稿:网友
 
国内最大的酷站演示中心!
首选,先要找一个开源的c#压缩组件。
如:icsharpcode.sharpziplib 下载地址:http://www.icsharpcode.net/opensource/sharpziplib/default.aspx
根据它的帮助你就可以做自己需要的东东了。
我在使用这个组件行,遇到了一个问题。
当压缩小文件时没有什么错误,一旦源文件达到150m时,它会让你的机器垮掉。(至少是我的机器)
为什么会这样,因为如果源文件是150m时,你就需要在内存申请一个150m大小的字节数组。好点的机器还没问题,一般的机器可就惨了。如果文件在大的话,好机器也受不了的。
为了解决大文件压缩的问题,可以使用分段压缩的方法。
private string createzipfile(string path,int m)
 {
 try
 {
 crc32 crc = new crc32();
 icsharpcode.sharpziplib.zip.zipoutputstream zipout=new icsharpcode.sharpziplib.zip.zipoutputstream(system.io.file.create(path+".zip"));
 system.io.filestream fs=system.io.file.openread(path);
 long pai=1024*1024*m;//每m兆写一次
 long forint=fs.length/pai+1;
 byte[] buffer=null;
 zipentry entry = new zipentry(system.io.path.getfilename(path));
 entry.size = fs.length;
 entry.datetime = datetime.now;
 zipout.putnextentry(entry);
 for(long i=1;i<=forint;i++)
 {
 if(pai*i<fs.length)
 {
 buffer = new byte[pai];
 fs.seek(pai*(i-1),system.io.seekorigin.begin);
 }
 else
 {
 if(fs.length<pai)
 {
 buffer = new byte[fs.length];
 }
 else
 {
 buffer = new byte[fs.length-pai*(i-1)];
 fs.seek(pai*(i-1),system.io.seekorigin.begin);
 }
 }
 fs.read(buffer,0,buffer.length);
 crc.reset();
 crc.update(buffer);
 zipout.write(buffer,0, buffer.length);
 zipout.flush();
 }
 fs.close();
 zipout.finish();
 zipout.close();
 system.io.file.delete(path);
 return path+".zip";
 }
 catch(exception ex)
 {
 string str=ex.message;
 return path;
 } 
 }