Imported from ScrewTurn Wiki page SharpZipLib_Updating.00000

DavidPierson 2010-11-02 04:19:56 +01:00 коммит произвёл Wiki Import
Родитель 8ccf198bfc
Коммит efd1359441
1 изменённых файлов: 93 добавлений и 0 удалений

93
Updating.md Normal file

@ -0,0 +1,93 @@
**How to use SharpZipLib to update Zip files**
This page shows how to update an existing zip file. Contents may be added, overwritten or deleted.
# Basic updating of a zip file
First example shows how to add or overwrite entries in a zip file on disk.
This concentrates on the essentials.
using ICSharpCode.SharpZipLib.Zip;
public void UpdateExistingZip() {
ZipFile zipFile = new ZipFile(@"c:\temp\existing.zip");
// Must call BeginUpdate to start, and CommitUpdate at the end.
zipFile.BeginUpdate();
zipFile.Password = "whatever"; // Only if a password is wanted on the new entry
// The "Add()" method will add or overwrite as necessary.
// When the optional entryName parameter is omitted, the entry will be named
// with the full folder path and without the drive e.g. "temp/folder/test1.txt".
//
zipFile.Add(@"c:\temp\folder\test1.txt");
// Specify the entryName parameter to modify the name as it appears in the zip.
//
zipFile.Add(@"c:\temp\folder\test2.txt", "test2.txt");
// Continue calling .Add until finished.
// Both CommitUpdate and Close must be called.
zipFile.CommitUpdate();
zipFile.Close();
}
# Updating a zip file in memory
Updating in memory is no more difficult than updating a disk file. The only real difference is setting IsStreamOwner.
// This will update a zip file contained in a memory stream.
public void UpdateZipInMemory(MemoryStream ms) {
// The memorystream is expected to contain the complete zipfile
ZipFile zipFile = new ZipFile(ms);
zipFile.BeginUpdate();
zipFile.Add(@"c:\temp\folder\test1.txt"); // Default naming
zipFile.Add(@"c:\temp\folder\test2.txt", "test2.txt"); // Explicit naming
// etc
// Both CommitUpdate and Close must be called.
zipFile.CommitUpdate();
// Set this so that Close does not close the memorystream
zipFile.IsStreamOwner = false;
zipFile.Close();
// Reposition to the start for the convenience of the caller.
ms.Position = 0;
}
// This is a test harnesss to check that the update in memory is working.
//
public void CallingExample() {
// Read a disk file into memory
MemoryStream ms = new MemoryStream();
FileStream fs = File.OpenRead(@"c:\temp\existing.zip");
// Copying whole file into a byte array is not efficient. Better to use StreamUtils.Copy as shown below.
byte[ ] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
ms.Write(bytes, 0, bytes.Length);
// Do the update
UpdateZipInMemory(ms);
// Save the update to disk
fs = File.Create(@"c:\temp\updated.zip");
// This utility method copies from stream to stream.
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(ms, fs, new byte[4096]);
fs.Close();
}
[[Back to Code Reference main page|Code Reference]]