如何使用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;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章