如何使用C#壓縮文件及注意的問題!
2024-07-21 02:19:06
供稿:網(wǎng)友
國(guó)內(nèi)最大的酷站演示中心!
首選,先要找一個(gè)開源的c#壓縮組件。
如:icsharpcode.sharpziplib 下載地址:http://www.icsharpcode.net/opensource/sharpziplib/default.aspx
根據(jù)它的幫助你就可以做自己需要的東東了。
我在使用這個(gè)組件行,遇到了一個(gè)問題。
當(dāng)壓縮小文件時(shí)沒有什么錯(cuò)誤,一旦源文件達(dá)到150m時(shí),它會(huì)讓你的機(jī)器垮掉。(至少是我的機(jī)器)
為什么會(huì)這樣,因?yàn)槿绻次募?50m時(shí),你就需要在內(nèi)存申請(qǐng)一個(gè)150m大小的字節(jié)數(shù)組。好點(diǎn)的機(jī)器還沒問題,一般的機(jī)器可就慘了。如果文件在大的話,好機(jī)器也受不了的。
為了解決大文件壓縮的問題,可以使用分段壓縮的方法。
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;
}
}