0

我的应用程序会将大量缓存数据存储到本地存储中,以实现性能和断开连接的目的。我尝试使用 SharpZipLib 来压缩创建的缓存文件,但我遇到了一些困难。

我可以创建文件,但它是无效的。Windows 内置的 zip 系统和 7-zip 都表明该文件无效。当我尝试通过 SharpZipLib 以编程方式打开文件时,出现异常“中央目录签名错误”。我认为部分问题是我直接从 MemoryStream 创建 zip 文件,因此没有“根”目录。不确定如何使用 SharpZipLib 以编程方式创建一个。

下面的 EntityManager 是 IdeaBlade DevForce 生成的“数据上下文”。它可以将其内容保存到流中,以便序列化到磁盘进行缓存。

这是我的代码:

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();    

                }
            }
        }
4

2 回答 2

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.
}
于 2011-04-15T15:37:51.963 回答
-2

删除outStream.Position = 0;它就可以了。

于 2011-11-01T23:02:55.243 回答