2014-04-10 38 views
0

我從磁盤讀取解壓縮的二進制文件是這樣的:如何將其轉換爲讀取zip文件?

string fn = @"c:\\MyBinaryFile.DAT"; 
byte[] ba = File.ReadAllBytes(fn); 
MemoryStream msReader = new MemoryStream(ba); 

我現在想通過使用壓縮二進制文件,以提高I/O速度。但是,我如何將它融入上述模式?

string fn = @"c:\\MyZippedBinaryFile.GZ"; 
//Put something here 
byte[] ba = File.ReadAllBytes(fn); 
//Or here 
MemoryStream msReader = new MemoryStream(ba); 

什麼是實現這個請求的最佳方式。

我需要結束一個MemoryStream,因爲我的下一步是反序列化它。

+1

檢查:[使用C#解壓加上.gz文件(http://stackoverflow.com/questions/1348198/unzipping-a-gz-file-using-c-sharp) – scheien

+0

什麼你有沒有嘗試過?你只是在尋找一個庫來解壓縮壓縮的東西嗎? – flindeberg

回答

1

您必須對文件內容使用GZipStream

所以基本上應該是這樣的:

string fn = @"c:\\MyZippedBinaryFile.GZ"; 
byte[] ba = File.ReadAllBytes(fn); 
using (MemoryStream msReader = new MemoryStream(ba)) 
using (GZipStream zipStream = new GZipStream(msReader, CompressionMode.Decompress)) 
{ 
    // Read from zipStream instead of msReader 
} 

爲了考慮通過flindenberg有效的評論,你也可以直接打開文件,而不必首先將整個文件讀入內存:

string fn = @"c:\\MyZippedBinaryFile.GZ"; 
using (FileStream stream = File.OpenRead(fn)) 
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress)) 
{ 
    // Read from zipStream instead of stream 
} 

您需要使用內存流就結了?沒問題:

string fn = @"c:\\MyZippedBinaryFile.GZ"; 
using (FileStream stream = File.OpenRead(fn)) 
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress)) 
using (MemoryStream ms = new MemoryStream() 
{ 
    zipStream.CopyTo(ms); 
    ms.Seek(0, SeekOrigin.Begin); // don't forget to rewind the stream! 

    // Read from ms 
} 
+0

爲什麼你要通過ReadAllBytes然後解壓?而不是打開文件作爲流和解壓縮,因此只保留文件的解壓縮版本在內存中? – flindeberg

+0

我從原始問題中儘可能多地獲取了代碼。 OP做到了這一點。當然你也可以直接在文件上打開一個'FileStream'。 –

+0

@ThorstenDittmar謝謝 - 但我需要結束與MemoryStream – ManInMoon

相關問題