白天有雨

此处应该有掌声

导航

如何使用C#压缩文件及注意的问题!

首选,先要找一个开源的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;
}
}

posted on 2005-12-31 15:02  卓如  阅读(463)  评论(0编辑  收藏  举报