怎么使用SharpZipLib.Silverlight4向目标压缩包追加文件?
目前遇到一个需求要求将文件追加到压缩包中去,使用的是SharpZip组件,ZipOutputStream流存储,我做了一个测试,代码如下:private void button1_Click(object sender, RoutedEventArgs e)
{
SaveToIs();
}
private void btnAddFile_Click(object sender, RoutedEventArgs e)
{
AddToZip();
}
/// <summary>
/// 文件名
/// </summary>
public static string Name { get; set; }
/// <summary>
/// 保存到存储器
/// </summary>
public static void SaveToIs()
{
Stream contentStream = null;
OpenFileDialog sfd = new OpenFileDialog
{
Filter = "文件|*.*",
};
if (sfd.ShowDialog() == true)
{
Name = sfd.File.Name;
contentStream = sfd.File.OpenRead();
SetStream(contentStream, Name);
}
}
/// <summary>
/// 从存储器读取
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static Stream GetStream(string name)
{
Stream stream;
using (IsolatedStorageFile myIsf = IsolatedStorageFile.GetUserStoreForApplication())
{
//检查是否存在
if (!myIsf.FileExists(name))
{
return null;
}
//打开流
var myIsfs = new IsolatedStorageFileStream(name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, myIsf);
stream = myIsfs;
}
return stream;
}
/// <summary>
/// 保存到存储器
/// </summary>
/// <param name="stream"></param>
/// <param name="name"></param>
public static void SetStream(Stream stream, string name)
{
Stream fileStream = stream;
using (var myIsf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var myIsfs = new IsolatedStorageFileStream(name, FileMode.OpenOrCreate, myIsf))
{
fileStream.CopyTo(myIsfs);//拷贝到独立存储
fileStream.Close();
}
}
}
/// <summary>
/// 添加至zip
/// </summary>
public static void AddToZip()
{
OpenFileDialog sfd = new OpenFileDialog
{
Filter = "压缩包|*.zip"
};
if (sfd.ShowDialog() == true)
{
Stream contentStream = new FileInfo(sfd.File.FullName).Open(FileMode.OpenOrCreate, FileAccess.ReadWrite);
var fs = GetStream(Name);
var s = new ZipOutputStream(contentStream);
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
var entry = new ZipEntry(Name);
s.SetLevel(9);
entry.CompressionMethod = CompressionMethod.Stored;
entry.IsUnicodeText = true;
fs.Close();
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
fs.Close();
s.Close();
}
}
但是这种做法很不理想,使用了
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
实现的是覆盖之前zip中的流的buffer.Length的大小。
由此想到在获取filestream,并且在创建ZipOutputStream之前,将filestream的Position指定到末尾位置,是不是就能实现追加,但是这种做法调试之后,压缩包损坏了。
有没有兄弟使用过SharpZip追加的援助一下!~ 压缩 silverlight ZipFile SharpZip
补充:.NET技术 , C#