public Delete ( string fileName ) : bool | ||
fileName | string | The filename to delete |
Результат | bool |
void TryDeleting(byte[] master, int totalEntries, int additions, params int[] toDelete) { MemoryStream ms = new MemoryStream(); ms.Write(master, 0, master.Length); using (ZipFile f = new ZipFile(ms)) { f.IsStreamOwner = false; Assert.AreEqual(totalEntries, f.Count); Assert.IsTrue(f.TestArchive(true)); f.BeginUpdate(new MemoryArchiveStorage()); for (int i = 0; i < additions; ++i) { f.Add(new StringMemoryDataSource("Another great file"), string.Format("Add{0}.dat", i + 1)); } foreach (int i in toDelete) { f.Delete(f[i]); } f.CommitUpdate(); /* write stream to file to assist debugging. byte[] data = ms.ToArray(); using ( FileStream fs = File.Open(@"c:\aha.zip", FileMode.Create, FileAccess.ReadWrite, FileShare.Read) ) { fs.Write(data, 0, data.Length); } */ int newTotal = totalEntries + additions - toDelete.Length; Assert.AreEqual(newTotal, f.Count, string.Format("Expected {0} entries after update found {1}", newTotal, f.Count)); Assert.IsTrue(f.TestArchive(true), "Archive test should pass"); } }
public void Delete(string filename) { pkg.BeginUpdate(); pkg.Delete(filename); pkg.CommitUpdate(); Commit(); }
private void SetSignatureFileContent(Stream packageStream, byte[] fileContent) { try { using (var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(packageStream)) { zipFile.IsStreamOwner = false; zipFile.BeginUpdate(); zipFile.Delete(SigningSpecifications.V1.SignaturePath); zipFile.CommitUpdate(); zipFile.BeginUpdate(); zipFile.Add( new StreamDataSource(new MemoryStream(fileContent)), SigningSpecifications.V1.SignaturePath, CompressionMethod.Stored); zipFile.CommitUpdate(); } packageStream.Position = 0; _packageStream = packageStream; } catch { packageStream?.Dispose(); throw; } }
public void AddAndDeleteEntries() { string tempFile = GetTempFilePath(); Assert.IsNotNull(tempFile, "No permission to execute this test?"); string addFile = Path.Combine(tempFile, "a.dat"); MakeTempFile(addFile, 1); string addFile2 = Path.Combine(tempFile, "b.dat"); MakeTempFile(addFile2, 259); tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using (ZipFile f = ZipFile.Create(tempFile)) { f.BeginUpdate(); f.Add(addFile); f.Add(addFile2); f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true)); } using (ZipFile f = new ZipFile(tempFile)) { Assert.AreEqual(2, f.Count); Assert.IsTrue(f.TestArchive(true)); f.BeginUpdate(); f.Delete(f[0]); f.CommitUpdate(); Assert.AreEqual(1, f.Count); Assert.IsTrue(f.TestArchive(true)); } File.Delete(addFile); File.Delete(addFile2); File.Delete(tempFile); }
private void SaveChannels(ZipFile zip, string fileName, ChannelList channels, byte[] fileContent) { if (fileContent == null) return; zip.Delete(fileName); string tempFilePath = Path.GetTempFileName(); using (var stream = new FileStream(tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { this.WriteChannels(channels, fileContent, stream); } zip.Add(tempFilePath, fileName); }
//[system]mapdata.txtファイルを書き出す関数 public void MakeMapDataFile() { //List<string> tmpList = new List<string>(); List <string> notUseList = new List <string>(); try { string str = ""; //ZIP書庫のパス string zipPath = PlayerPrefs.GetString("進行中シナリオ", ""); //書庫に追加するファイルのパス string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "[system]mapdata[system].txt"; //先に[system]mapdata.txtを一時的に書き出しておく。 for (int i = 0; i < mapData.Count; i++) { if (mapData[i].Replace("\n", "").Replace("\r", "") == "") { continue; } str = str + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n"; } str = str + "[END]"; System.IO.File.WriteAllText(file, str); //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath); zf.Password = Secret.SecretString.zipPass; //先にzip上のmapdataを更新しておく(以降でzip上のmapdataを基に、使っているファイルを判別して不使用ファイルを消す操作をするから) //ZipFileの更新を開始 zf.BeginUpdate(); //ZIP書庫に一時的に書きだしておいたファイルを追加する zf.Add(file, System.IO.Path.GetFileName(file)); //ZipFileの更新をコミット zf.CommitUpdate(); //以下、不使用データの削除処理 ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry("[system]mapdata[system].txt"); tmpList.Clear(); FileSearchLoop(ze, zf); tmpList.Add("[system]mapdata[system].txt"); tmpList.Add("[system]password[system].txt"); tmpList.Add("[system]commandFileNum[system].txt"); tmpList.Add("[system]command1[system]PC版スタート地点[system].txt"); tmpList.Add("[system]PC版スタート地点[system].txt"); foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze3 in zf) { bool useFlag = false; foreach (string tmpStr in tmpList) { if (tmpStr == ze3.Name) { useFlag = true; } } if (useFlag == false) { string tmpStr = ze3.Name; notUseList.Add(tmpStr); } } //ZipFileの更新を開始 zf.BeginUpdate(); foreach (string tmpStr in notUseList) { zf.Delete(tmpStr); } //notUseListのファイルを消す。 //ZipFileの更新をコミット zf.CommitUpdate(); //閉じる zf.Close(); //一時的に書きだした[system]mapdata.txtを消去する。 System.IO.File.Delete(file); } catch { } }
private void ZipFiles() { const string entryName = "chmgt_type001/" + FILE_chmgt_db; using (var zip = new ZipFile(this.FileName)) { zip.BeginUpdate(); zip.Delete(entryName); zip.Add(this.tempDir + "chmgt.db", entryName); zip.CommitUpdate(); } }
/// <summary> /// Delete entries from an archive /// </summary> /// <param name="fileSpecs">The file specs to operate on.</param> void Delete(ArrayList fileSpecs) { string zipFileName = fileSpecs[0] as string; if (Path.GetExtension(zipFileName).Length == 0) { zipFileName = Path.ChangeExtension(zipFileName, ".zip"); } try { using (ZipFile zipFile = new ZipFile(zipFileName)) { zipFile.BeginUpdate(); for ( int i = 1; i < fileSpecs.Count; ++i ) { zipFile.Delete((string)fileSpecs[i]); } zipFile.CommitUpdate(); } } catch(Exception ex) { Console.WriteLine("Problem deleting files - '{0}'", ex.Message); } }
void DeleteContent(string loc) { ZipFile zipFile = new ZipFile(FileLoc); // Must call BeginUpdate to start, and CommitUpdate at the end. zipFile.BeginUpdate(); zipFile.Delete(loc); // Both CommitUpdate and Close must be called. zipFile.CommitUpdate(); zipFile.Close(); }
private void groupBox1_DragDrop(object sender, DragEventArgs e) { try { modInstallerLabel.Text = Util.langNode("adding"); string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); ZipFile zf = new ZipFile(jarList.SelectedNode.Name); String comment = zf.ZipFileComment + "\r\n--- " + DateTime.Now + " " + Util.langNode("addedthesefiles") + " ---\r\n"; zf.BeginUpdate(); int i = 0; foreach (string file in files) { Console.WriteLine("Adding " + file); if (((File.GetAttributes(file) & FileAttributes.Directory) == FileAttributes.Directory)) { System.Console.WriteLine("It is a directory!"); //zf.AddDirectory(dirname); string[] filesindir = Directory.GetFiles(file, "*", SearchOption.AllDirectories); // Display all the files. foreach (string fileindir in filesindir) { Console.WriteLine("Adding " + fileindir.Replace(Directory.GetParent(file).FullName, "")); zf.Add(fileindir, fileindir.Replace(Directory.GetParent(file).FullName, "")); comment += fileindir.Replace(Directory.GetParent(file).FullName, "") + "\r\n"; i++; } } else { zf.Add(file, System.IO.Path.GetFileName(file)); comment += System.IO.Path.GetFileName(file) + "\r\n"; i++; } } ZipEntry mi = zf.GetEntry("META-INF"); if (mi != null) { zf.Delete(mi); comment += String.Format(Util.langNode("removedfile"), "META-INF") + "\r\n"; } zf.SetComment(comment); jarCommentBox.Text = comment; zf.CommitUpdate(); zf.Close(); modInstallerLabel.Text = String.Format(Util.langNode("addedfiles"), i); } catch (Exception ex) { System.Console.WriteLine("Could not write: " + ex.Message + "\r\n" + ex.StackTrace); modInstallerLabel.Text = String.Format(Util.langNode("errordetail"), ex.Message); } }
/// <summary> /// delete image file inside the zip file, or return a name of file to delete on the hard drive. /// Make sure you dispose of this PhotoDescr before deleting the file. /// </summary> public string deleteFromDisk() { string ret = null; if(this.imageSourceIsLocal) { // make sure the image is not used/locked and we can actually delete it: releaseImage(); ImageCache.releaseImage(m_imageFileName); GC.Collect(); int pos = m_imageFileName.IndexOf("|"); if(pos >= 0) { // this is a .zip or .gpz file string zipFileName = m_imageFileName.Substring(0, pos); if (!File.Exists(zipFileName)) { LibSys.StatusBar.Error("Failed to open Zip"); throw new InvalidOperationException("'" + zipFileName + "' not found or not a valid zip file"); } using (ZipFile zip = new ZipFile(zipFileName)) { string photoFileName = m_imageFileName.Substring(pos + 1); ZipEntry zipEntry = zip.GetEntry(photoFileName); if (zipEntry != null) { zip.BeginUpdate(); zip.Delete(zipEntry); } else { zip.Close(); throw new InvalidOperationException("'" + photoFileName + "' is not found inside " + zipFileName); } zip.CommitUpdate(); } } else { ret = m_imageFileName; } } return ret; }
void DeleteContent(string loc) { ZipFile zipFile = new ZipFile(this.zipArchive); // Must call BeginUpdate to start, and CommitUpdate at the end. zipFile.BeginUpdate(); zipFile.Delete(loc); // Both CommitUpdate and Close must be called. zipFile.CommitUpdate(); zipFile.IsStreamOwner = false; zipFile.Close(); this.zipArchive.Position = 0; }
public override void Save(string tvOutputFile) { if (tvOutputFile != this.FileName) { File.Copy(this.FileName, tvOutputFile); this.FileName = tvOutputFile; } using (var zip = new ZipFile(this.FileName)) { zip.BeginUpdate(); foreach (var channelList in this.DataRoot.ChannelLists) { var dbPath = this.dbPathByChannelList[channelList]; SaveChannelList(channelList, dbPath); var entryName = Path.GetFileName(dbPath); zip.Delete(entryName); zip.Add(dbPath, entryName); } zip.CommitUpdate(); } }
public static void RemoveSignatures(string jar) { // Ensures the specified package has no signatures to speak of. using (var zip = new ZipFile(jar)) { zip.BeginUpdate(); var entry = zip.GetEntry("META-INF/MANIFEST.MF"); if (entry != null) zip.Delete(entry); zip.GetEntry("META-INF/MOJANG_C.SF"); if (entry != null) zip.Delete(entry); zip.GetEntry("META-INF/MOJANG_C.DSA"); if (entry != null) zip.Delete(entry); zip.CommitUpdate(); } }
public void AddToEmptyArchive() { string tempFile = GetTempFilePath(); Assert.IsNotNull(tempFile, "No permission to execute this test?"); string addFile = Path.Combine(tempFile, "a.dat"); MakeTempFile(addFile, 1); using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { try { tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using (ZipFile f = ZipFile.Create(tempFile)) { f.BeginUpdate(); f.Add(addFile); f.CommitUpdate(); Assert.AreEqual(1, f.Count); Assert.IsTrue(f.TestArchive(true)); } using (ZipFile f = new ZipFile(tempFile)) { Assert.AreEqual(1, f.Count); f.BeginUpdate(); f.Delete(f[0]); // failing here in 4 and 3 - fixed - one-off in zipfile f.CommitUpdate(); Assert.AreEqual(0, f.Count); Assert.IsTrue(f.TestArchive(true)); f.Close(); } store.DeleteFile(tempFile); } finally { store.DeleteFile(addFile); } } }
private IEnumerator NCBIE(string str1, string str2, bool flag) { int inum = 0; string tmp1, tmp2; List <string> tmpList = new List <string>(); tmp1 = "[system]" + str1 + ".txt"; tmp2 = str2; //全てのコマンドファイル、イベントファイル、マップデータを開き、コマンド名([system]~~××.txt)をtmp1に、イベント名(××.txt)をtmp2に変換する。 //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in zf) { if ((ze.Name != tmp2 && ze.Name == tmp1)) { //他のイベントと名前がかぶっていれば、名前変更ではなくイベント紐付けが目的だと判断。コピーはしない。 zf.Close(); yield break; } } //ZipFileの更新を開始 zf.BeginUpdate(); //展開するエントリを探す foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in zf) { if (ze.Name.Substring(ze.Name.Length - 4) == ".txt" && !tmpList.Contains(ze.Name) && ze.Name != "[system]mapdata[system].txt") { //閲覧するZIPエントリのStreamを取得 Stream reader = zf.GetInputStream(ze); //文字コードを指定してStreamReaderを作成 StreamReader sr = new StreamReader( reader, System.Text.Encoding.GetEncoding("UTF-8")); // テキストを取り出す string text = sr.ReadToEnd(); sr.Close(); reader.Close(); string text2 = text; // 読み込んだ目次テキストファイルからstring配列を作成する text = text.Replace(tmp2, tmp1); if (text2 == text) { continue; } StreamWriter sw = new StreamWriter(@GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp" + inum.ToString() + ".txt", false, System.Text.Encoding.GetEncoding("UTF-8")); //TextBox1.Textの内容を書き込む sw.Write(text); //閉じる sw.Close(); //ファイル名自体も置換 string tmpName; tmpName = ze.Name; tmpName = tmpName.Replace(tmp2, tmp1); if (flag == false) { zf.Delete(ze.Name); } //他から関連付けされていないなら、旧コマンドファイルはもう使わないので削除。 zf.Add("tmp" + inum.ToString() + ".txt", tmpName); inum++; tmpList.Add(tmpName); } } //ZipFileの更新をコミット zf.CommitUpdate(); //閉じる zf.Close(); for (int i = 0; i < inum; i++) { File.Delete(@GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp" + i.ToString() + ".txt"); } for (int i = 0; i < undoList.Count; i++) { undoList[i] = undoList[i].Replace(tmp2, tmp1); } }
public static void savePhotoParameters(Form ownerForm, string folderOrZipName) { if (Project.photoParametersDonotwrite) { return; } if (AllFormats.isZipFile(folderOrZipName)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Zip file not found: " + folderOrZipName); return; } string ppfName = folderOrZipName + "|" + Project.PHOTO_PARAM_FILE_NAME; string message = "Confirm: will write new Camera Time Shift to " + ppfName + "\n\nDo you want to create/overwrite the file (inside the ZIP archive)?"; if (!Project.photoParametersAsk || Project.YesNoBox(ownerForm, message)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Failed to open Zip file: " + folderOrZipName); return; } XmlDocument xmlDoc = null; using (ZipFile zip = new ZipFile(folderOrZipName)) { ZipEntry entry = zip.GetEntry(Project.PHOTO_PARAM_FILE_NAME); if (entry == null) { LibSys.StatusBar.Trace("IP: creating photo parameters entry: " + folderOrZipName + "|" + Project.PHOTO_PARAM_FILE_NAME); xmlDoc = makePhotoParametersXmlDoc(); zip.BeginUpdate(); } else { string fileName = entry.Name; LibSys.StatusBar.Trace("IP: existing photo parameters entry: " + folderOrZipName + "|" + fileName); xmlDoc = new XmlDocument(); Stream stream = zip.GetInputStream(entry); using (StreamReader rdr = new StreamReader(stream)) { xmlDoc.LoadXml(rdr.ReadToEnd()); } editPhotoParametersXmlDoc(xmlDoc); zip.BeginUpdate(); zip.Delete(entry); } StringMemoryDataSource m = new StringMemoryDataSource(xmlDoc.OuterXml); zip.Add(m, Project.PHOTO_PARAM_FILE_NAME); lastPhotoParametersFileName = ppfName; zip.CommitUpdate(); } } } else { if (!Directory.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Folder not found: " + folderOrZipName); return; } string ppfName = Path.Combine(folderOrZipName, Project.PHOTO_PARAM_FILE_NAME); string message = "Confirm: will write new Camera Time Shift to " + ppfName + "\n\nDo you want to " + (File.Exists(ppfName) ? "overwrite" : "create") + " the file?"; if (!Project.photoParametersAsk || Project.YesNoBox(ownerForm, message)) { try { if (File.Exists(ppfName)) { LibSys.StatusBar.Trace("IP: existing photo parameters file: " + ppfName); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(ppfName); editPhotoParametersXmlDoc(xmlDoc); xmlDoc.Save(ppfName); lastPhotoParametersFileName = ppfName; } else { LibSys.StatusBar.Trace("IP: creating photo parameters file: " + ppfName); XmlDocument xmlDoc = makePhotoParametersXmlDoc(); xmlDoc.Save(ppfName); lastPhotoParametersFileName = ppfName; } } catch (Exception e) { LibSys.StatusBar.Error("DlgPhotoManager:savePhotoParameters() " + e.Message); } } } }
public static void savePhotoPositions(Form ownerForm, string folderOrZipName) { if (Project.photoPositionsDonotwrite) { return; } XmlDocument xmlDoc = makePhotoPositionsXmlDoc(); if (AllFormats.isZipFile(folderOrZipName)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Zip file not found: " + folderOrZipName); return; } string ppfName = folderOrZipName + "|" + Project.PHOTO_POSITIONS_FILE_NAME; string message = "Confirm: will write photo positions to " + ppfName + "\n\nDo you want to create/overwrite the file (inside the ZIP archive)?"; if (!Project.photoPositionsAsk || Project.YesNoBox(ownerForm, message)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Failed to open Zip file: " + folderOrZipName); return; } using (ZipFile zip = new ZipFile(folderOrZipName)) { ZipEntry entry = zip.GetEntry(Project.PHOTO_POSITIONS_FILE_NAME); if (entry == null) { LibSys.StatusBar.Trace("IP: creating photo positions entry: " + folderOrZipName + "|" + Project.PHOTO_POSITIONS_FILE_NAME); zip.BeginUpdate(); } else { string fileName = entry.Name; LibSys.StatusBar.Trace("IP: existing photo positions entry: " + folderOrZipName + "|" + fileName); zip.BeginUpdate(); zip.Delete(entry); } StringMemoryDataSource m = new StringMemoryDataSource(xmlDoc.OuterXml); zip.Add(m, Project.PHOTO_POSITIONS_FILE_NAME); zip.CommitUpdate(); } } } else { if (!Directory.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Folder not found: " + folderOrZipName); return; } string ppfName = Path.Combine(folderOrZipName, Project.PHOTO_POSITIONS_FILE_NAME); try { if (File.Exists(ppfName)) { LibSys.StatusBar.Trace("IP: existing photo positions file: " + ppfName); } else { LibSys.StatusBar.Trace("IP: creating photo positions file: " + ppfName); } xmlDoc.Save(ppfName); } catch (Exception e) { LibSys.StatusBar.Error("DlgPhotoManager:savePhotoPositions() " + e.Message); } } }
private void Flush(bool refresh) { lock (this) { var filesChanged = zipFileInfos.Values.Where(c => c.ShadowFile != null).ToList(); var filesDeleted = zipFileInfos.Values.Where(c => !c.Exists && c.ZipEntry != null).ToList(); var setOfPreviousDirectories = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); foreach (ZLib.ZipEntry zipEntry in zipFile) { if (zipEntry.IsDirectory) { setOfPreviousDirectories.Add("/" + zipEntry.Name.Substring(0, zipEntry.Name.Length - 1)); } else { var x = zipEntry.Name.LastIndexOf('/'); if (x > 0) { var path = zipEntry.Name.Substring(0, x); setOfPreviousDirectories.Add("/" + path); } } } var setOfCurrentImplicitDirectories = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); var setOfCurrentDirectories = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); foreach (var zipFileInfo in zipFileInfos.Values) { if (zipFileInfo.Exists) { var x = zipFileInfo.AbsolutePath.LastIndexOf('/'); if (x > 0) { var path = zipFileInfo.AbsolutePath.Substring(0, x); setOfCurrentDirectories.Add(path); setOfCurrentImplicitDirectories.Add(path); } } } foreach (var zipDirectoryInfo in zipDirectoryInfos.Values.Where(c => c.Exists)) { setOfCurrentDirectories.Add(zipDirectoryInfo.AbsolutePath); } var setOfNewDirectories = new HashSet <string>(setOfCurrentDirectories.Where(c => !setOfPreviousDirectories.Contains(c)), StringComparer.InvariantCultureIgnoreCase); var setOfDeletedDirectories = new HashSet <string>(setOfPreviousDirectories.Where(c => !setOfCurrentDirectories.Contains(c)), StringComparer.InvariantCultureIgnoreCase); var setOfDirectoriesToCreate = new HashSet <string>(setOfNewDirectories.Where(c => !setOfCurrentImplicitDirectories.Contains(c)), StringComparer.InvariantCultureIgnoreCase); setOfDirectoriesToCreate.Remove("/"); if (filesChanged.Count > 0 || filesDeleted.Count > 0) { zipFile.BeginUpdate(); try { foreach (var zipFileInfo in filesChanged) { var shadowFile = zipFileInfo.ShadowFile; var name = zipFileInfo.AbsolutePath; try { zipFile.Add(new StreamDataSource(shadowFile.GetContent().GetInputStream()), name); } catch (FileNodeNotFoundException) { } } foreach (var zipFileInfo in filesDeleted) { zipFile.Delete(zipFileInfo.ZipEntry); } foreach (var directoryToCreate in setOfDirectoriesToCreate) { zipFile.AddDirectory(directoryToCreate); } foreach (var directory in setOfDeletedDirectories) { // SharpZipLib currently doesn't support removing explicit directories } } finally { zipFile.CommitUpdate(); } } if (refresh) { this.RefreshNodeInfos(); } } }
/// <summary> /// Delete entries from an archive /// </summary> /// <param name="fileSpecs">The file specs to operate on.</param> void Delete(ArrayList fileSpecs) { var zipFileName = fileSpecs[0] as string; if (Path.GetExtension(zipFileName).Length == 0) { zipFileName = Path.ChangeExtension(zipFileName, ".zip"); } using (ZipFile zipFile = new ZipFile(zipFileName)) { zipFile.BeginUpdate(); for ( int i = 1; i < fileSpecs.Count; ++i ) { zipFile.Delete((string)fileSpecs[i]); } zipFile.CommitUpdate(); } }
/// <summary> /// Commits the updates. /// </summary> /// <remarks>Documented by Dev03, 2009-07-20</remarks> public void CommitUpdates() { ZipFile zipFile = null; try { zipFile = new ZipFile(file.FullName); zipFile.UseZip64 = UseZip64.Off; // AAB-20090720: Zip64 caused some problem when modifing the archive (ErrorReportHandler.cs) - Zip64 is required to bypass the 4.2G limitation of the original Zip format (http://en.wikipedia.org/wiki/ZIP_(file_format)) ZipEntry errorReport = zipFile.GetEntry(Resources.ERRORFILE_NAME); MemoryStream stream = new MemoryStream(); using (Stream s = GetZipStream(errorReport, zipFile)) { XmlDocument doc = new XmlDocument(); using (StreamReader reader = new StreamReader(s, Encoding.Unicode)) { doc.LoadXml(reader.ReadToEnd()); } foreach (Dictionary<string, string> value in values) { XmlElement xE = doc.CreateElement(value["nodeName"]); xE.InnerText = value["value"].Trim(); XmlNode parentNode = doc.SelectSingleNode(value["parentPath"]); if (parentNode == null) return; parentNode.AppendChild(xE); } doc.Save(stream); } ZipData data = new ZipData(stream); zipFile.BeginUpdate(); zipFile.Delete(errorReport); //delete first! zipFile.CommitUpdate(); zipFile.BeginUpdate(); zipFile.Add(data, errorReport.Name); zipFile.CommitUpdate(); } finally { if (zipFile != null) zipFile.Close(); } }
/// <summary> /// Removes the file. /// </summary> /// <param name="filename">The filename.</param> /// <remarks>Documented by Dev03, 2009-07-16</remarks> public void RemoveFile(string filename) { ZipFile zipFile = null; try { zipFile = new ZipFile(file.FullName); zipFile.BeginUpdate(); zipFile.Delete(zipFile.GetEntry(filename)); zipFile.CommitUpdate(); } finally { if (zipFile != null) zipFile.Close(); } }
void TryDeleting(byte[] master, int totalEntries, int additions, params string[] toDelete) { MemoryStream ms = new MemoryStream(); ms.Write(master, 0, master.Length); using (ZipFile f = new ZipFile(ms)) { f.IsStreamOwner = false; Assert.AreEqual(totalEntries, f.Count); Assert.IsTrue(f.TestArchive(true)); f.BeginUpdate(new MemoryArchiveStorage()); for (int i = 0; i < additions; ++i) { f.Add(new StringMemoryDataSource("Another great file"), string.Format("Add{0}.dat", i + 1)); } foreach (string name in toDelete) { f.Delete(name); } f.CommitUpdate(); // write stream to file to assist debugging. // WriteToFile(@"c:\aha.zip", ms.ToArray()); int newTotal = totalEntries + additions - toDelete.Length; Assert.AreEqual(newTotal, f.Count, string.Format("Expected {0} entries after update found {1}", newTotal, f.Count)); Assert.IsTrue(f.TestArchive(true), "Archive test should pass"); } }
public void AddToEmptyArchive() { string tempFile = GetTempFilePath(); Assert.IsNotNull(tempFile, "No permission to execute this test?"); string addFile = Path.Combine(tempFile, "a.dat"); MakeTempFile(addFile, 1); try { tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using ( ZipFile f = ZipFile.Create(tempFile) ) { f.BeginUpdate(); f.Add(addFile); f.CommitUpdate(); Assert.AreEqual(1, f.Count); Assert.IsTrue(f.TestArchive(true)); } using ( ZipFile f = new ZipFile(tempFile) ) { Assert.AreEqual(1, f.Count); f.BeginUpdate(); f.Delete(f[0]); f.CommitUpdate(); Assert.AreEqual(0, f.Count); Assert.IsTrue(f.TestArchive(true)); f.Close(); } File.Delete(tempFile); } finally { File.Delete(addFile); } }