2011-04-08 221 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;它的工作原理。