我的应用程序将大量缓存数据存储到本地存储,以实现性能和断开连接的目的。我曾尝试使用SharpZipLib压缩创建的缓存文件,但我遇到了一些困难。
我可以创建文件,但它无效。 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 :(得分: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 :(得分:-1)
删除outStream.Position = 0;
然后就可以了。