如何使用C#壓縮檔及注意的問題!

來源:互聯網
上載者:User
問題|壓縮 首選,先要找一個開源的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;
}
}




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.