2012-06-26 63 views
2

我想在C#中創建一個zip文件,它將包含幾乎8 GB的數據。我使用下面的代碼:如何在C#中使用SharpZipLib創建超過7 GB的zip文件?

using (var zipStream = new ZipOutputStream(System.IO.File.Create(outPath))) 
{ 
    zipStream.SetLevel(9); // 0-9, 9 being the highest level of compression 

    var buffer = new byte[1024*1024]; 

    foreach (var file in filenames) 
    { 
     var entry = new ZipEntry(Path.GetFileName(file)) { DateTime = DateTime.Now }; 

     zipStream.PutNextEntry(entry); 

     var bufferSize = BufferedSize; 
     using (var fs = new BufferedStream(System.IO.File.OpenRead(file), bufferSize)) 
     { 
      int sourceBytes; 
      do 
      { 
       sourceBytes = fs.Read(buffer, 0, buffer.Length); 
       zipStream.Write(buffer, 0, sourceBytes); 
      } while (sourceBytes > 0); 
     } 
    } 

    zipStream.Finish(); 
    zipStream.Close(); 
} 

此代碼對小文件下1 GB,但是當數據達到7-8 GB它拋出一個異常。

+4

什麼是例外? –

+0

這是爲什麼downvoted?這是一個有效的問題,不是嗎? –

+2

@PhilipDaubmeier也許因爲這個問題沒有包含有關異常的任何信息? –

回答

1

您正在使用SharpZipLib,對嗎?我不確定這是否是有效的解決方案,因爲我不知道它會拋出什麼異常,但是基於this postthis post,它可能是Zip64的問題。要麼使它用類似下面的代碼(從第二聯動後):基於第一後

UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off 

,或者,指定當您創建歸檔文件的大小,它應該自動採取Zip64的護理問題。示例代碼直接從第一個鏈接的文章:

using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipFilePath))) 
{ 
//Compression level 0-9 (9 is highest) 
zipStream.SetLevel(GetCompressionLevel()); 

//Add an entry to our zip file 
ZipEntry entry = new ZipEntry(Path.GetFileName(sourceFilePath)); 
entry.DateTime = DateTime.Now; 
/* 
* By specifying a size, SharpZipLib will turn on/off UseZip64 based on the file sizes. If Zip64 is ON 
* some legacy zip utilities (ie. Windows XP) who can't read Zip64 will be unable to unpack the archive. 
* If Zip64 is OFF, zip archives will be unable to support files larger than 4GB. 
*/ 
entry.Size = new FileInfo(sourceFilePath).Length; 
zipStream.PutNextEntry(entry); 

byte[] buffer = new byte[4096]; 
int byteCount = 0; 

using (FileStream inputStream = File.OpenRead(sourceFilePath)) 
{ 
    byteCount = inputStream.Read(buffer, 0, buffer.Length); 
    while (byteCount > 0) 
    { 
     zipStream.Write(buffer, 0, byteCount); 
     byteCount = inputStream.Read(buffer, 0, buffer.Length); 
    } 
} 
} 
5

正如其他人指出的那樣,實際的例外將有助於很多回答這個問題。但是,如果您想要更簡單的方式創建zip文件,我建議您嘗試DotNetZip庫,網址爲http://dotnetzip.codeplex.com/。我知道它支持Zip64(即大於4.2GB的條目,然後是65535條目),所以它可能能夠解決您的問題。使用filestreams和bytearrays自己也很容易。

using (ZipFile zip = new ZipFile()) { 
    zip.CompressionLevel = CompressionLevel.BestCompression; 
    zip.UseZip64WhenSaving = Zip64Option.Always; 
    zip.BufferSize = 65536*8; // Set the buffersize to 512k for better efficiency with large files 

    foreach (var file in filenames) { 
     zip.AddFile(file); 
    } 
    zip.Save(outpath); 
} 
相關問題