2011-04-08 181 views
0

我的應用程序將存儲大量緩存數據到本地存儲以實現性能和斷開連接的目的。我試圖使用SharpZipLib來壓縮創建的緩存文件,但我遇到了一些困難。以編程方式創建ZIP文件

我可以得到創建的文件,但它是無效的。 Windows內置的zip系統和7-zip都表明該文件無效。當我試圖通過SharpZipLib以編程方式打開文件時,我收到異常「錯誤的中央目錄簽名」。我認爲問題的一部分是我直接從MemoryStream創建zip文件,所以沒有「root」目錄。不知道如何用SharpZipLib以編程方式創建一個。

下面的EntityManager是IdeaBlade DevForce生成的「datacontext」。它可以將其內容保存到流中,以便序列化到磁盤進行緩存。

這裏是我的代碼:

private void SaveCacheFile(string FileName, EntityManager em) 
     { 
      using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(FileName, System.IO.FileMode.CreateNew, isf)) 
       { 
        MemoryStream inStream = new MemoryStream(); 
        MemoryStream outStream = new MemoryStream(); 
        Crc32 crc = new Crc32(); 
        em.CacheStateManager.SaveCacheState(inStream, false, true); 
        inStream.Position = 0; 

        ZipOutputStream zipStream = new ZipOutputStream(outStream); 
        zipStream.IsStreamOwner = false; 
        zipStream.SetLevel(3); 

        ZipEntry newEntry = new ZipEntry(FileName); 
        byte[] buffer = new byte[inStream.Length]; 
        inStream.Read(buffer, 0, buffer.Length); 
        newEntry.DateTime = DateTime.Now; 
        newEntry.Size = inStream.Length; 
        crc.Reset(); 
        crc.Update(buffer); 
        newEntry.Crc = crc.Value; 
        zipStream.PutNextEntry(newEntry); 
        buffer = null; 

        outStream.Position = 0; 
        inStream.Position = 0;     
        StreamUtils.Copy(inStream, zipStream, new byte[4096]); 
        zipStream.CloseEntry(); 
        zipStream.Finish(); 
        zipStream.Close(); 
        outStream.Position = 0; 
        StreamUtils.Copy(outStream, isfs, new byte[4096]); 
        outStream.Close();  

       } 
      } 
     } 

回答

0

從內存中創建一個zip文件直接是不是你的問題。 SharpZipLib使用ZipEntry構造函數中的參數來確定路徑,並且不關心該路徑是否具有子目錄。

using (ZipOutputStream zipStreamOut = new ZipOutputStream(outputstream)) 
{ 
    zipStreamOut.PutNextEntry(new ZipEntry("arbitrary.ext")); 
    zipstreamOut.Write(mybytearraydata, 0, mybytearraydata.Length); 
    zipStreamOut.Finish(); 
    //Line below needed if outputstream is a MemoryStream and you are 
    //passing it to a function expecting a stream. 
    outputstream.Position = 0; 

    //DoStuff. Optional; Not necessary if e.g., outputstream is a FileStream. 
} 
-1

刪除outStream.Position = 0;它的工作原理。