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"); } }
/// <summary> /// Add files to an existing Zip archive, /// </summary> /// <param name="filename">Array of path / filenames to add to the archive</param> /// <param name="archive">Zip archive that we want to add the file to</param> public void AddToZip(string[] filename, string archive) { if (!File.Exists(archive)) { return; } try { ZipFile zf = new ZipFile(archive); zf.BeginUpdate(); // path relative to the archive zf.NameTransform = new ZipNameTransform(Path.GetDirectoryName(archive)); foreach (var file in filename) { // skip if this isn't a real file if (!File.Exists(file)) { continue; } zf.Add(file, CompressionMethod.Deflated); } zf.CommitUpdate(); zf.Close(); } catch (Exception e) { if (e.Message != null) { var msg = new[] { e.Message }; LocDB.Message("defErrMsg", e.Message, msg, LocDB.MessageTypes.Error, LocDB.MessageDefault.First); } } }
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 Update(string filename, byte[] contents) { pkg.BeginUpdate(); pkg.Add(new StaticStreamDataSource(new MemoryStream(contents)), filename); pkg.CommitUpdate(); Commit(); }
public void CompressDataInToFile(string directory, string password, string outputFile) { var fullFileListing = Directory.EnumerateFiles(directory, "*.*", SearchOption.AllDirectories); var directories = Directory.EnumerateDirectories(directory, "*", SearchOption.AllDirectories); _logger.Information("Creating ZIP File"); using (var zip = new ZipFile(outputFile)) { zip.UseZip64 = UseZip64.On; _logger.Information("Adding directories.."); foreach (var childDirectory in directories) { _logger.Information(string.Format("Adding {0}", childDirectory.Replace(directory, string.Empty))); zip.BeginUpdate(); zip.AddDirectory(childDirectory.Replace(directory, string.Empty)); zip.CommitUpdate(); } _logger.Information("Adding files.."); foreach (var file in fullFileListing) { _logger.Information(string.Format("Adding {0}", file.Replace(directory, string.Empty))); zip.BeginUpdate(); zip.Add(file, file.Replace(directory, string.Empty)); zip.CommitUpdate(); } _logger.Information("Setting password.."); zip.BeginUpdate(); zip.Password = password; zip.CommitUpdate(); } }
public void MakePasswordFile() { try { //ZIP書庫のパス string zipPath = PlayerPrefs.GetString("進行中シナリオ", ""); //書庫に追加するファイルのパス string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "[system]password[system].txt"; //先に[system]password.txtを一時的に書き出しておく。 System.IO.File.WriteAllText(file, GameObject.Find("PassWordInput").GetComponent <InputField>().text); //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(); //閉じる zf.Close(); //一時的に書きだした[system]password.txtを消去する。 System.IO.File.Delete(file); } catch { } }
static public void CompressFolder(string aFolderName, string aFullFileOuputName, string[] ExcludedFolderNames, string[] ExcludedFileNames){ // Perform some simple parameter checking. More could be done // like checking the target file name is ok, disk space, and lots // of other things, but for a demo this covers some obvious traps. if (!Directory.Exists(aFolderName)) { Debug.Log("Cannot find directory : " + aFolderName); return; } try { string[] exFileNames = new string[0]; string[] exFolderNames = new string[0]; if(ExcludedFileNames != null) exFileNames = ExcludedFileNames; if(ExcludedFolderNames != null) exFolderNames = ExcludedFolderNames; // Depending on the directory this could be very large and would require more attention // in a commercial package. List<string> filenames = GenerateFolderFileList(aFolderName, null); //foreach(string filename in filenames) Debug.Log(filename); // 'using' statements guarantee the stream is closed properly which is a big source // of problems otherwise. Its exception safe as well which is great. using (ZipOutputStream zipOut = new ZipOutputStream(File.Create(aFullFileOuputName))){ zipOut.Finish(); zipOut.Close(); } using(ZipFile s = new ZipFile(aFullFileOuputName)){ s.BeginUpdate(); int counter = 0; //add the file to the zip file foreach(string filename in filenames){ bool include = true; string entryName = filename.Replace(aFolderName, ""); //Debug.Log(entryName); foreach(string fn in exFolderNames){ Regex regEx = new Regex(@"^" + fn.Replace(".",@"\.")); if(regEx.IsMatch(entryName)) include = false; } foreach(string fn in exFileNames){ Regex regEx = new Regex(@"^" + fn.Replace(".",@"\.")); if(regEx.IsMatch(entryName)) include = false; } if(include){ s.Add(filename, entryName); } counter++; } //commit the update once we are done s.CommitUpdate(); //close the file s.Close(); } } catch(Exception ex) { Debug.Log("Exception during processing" + ex.Message); // No need to rethrow the exception as for our purposes its handled. } }
/// <summary> /// 多文件打包下载 /// </summary> public void DwonloadZip(string[] filePathList, string zipName) { MemoryStream ms = new MemoryStream(); byte[] buffer = null; var context = HttpContext.Current; using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms)) { file.BeginUpdate(); file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。 foreach (var it in filePathList) { file.Add(context.Server.MapPath(it)); } file.CommitUpdate(); buffer = new byte[ms.Length]; ms.Position = 0; ms.Read(buffer, 0, buffer.Length); } context.Response.AddHeader("content-disposition", "attachment;filename=" + context.Server.UrlEncode(zipName)); context.Response.BinaryWrite(buffer); context.Response.ContentEncoding = System.Text.Encoding.UTF8; context.Response.Flush(); context.Response.End(); }
private void ZipMake(string scenarioName, string scenarioPass) { string str = "[END]"; string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "[system]mapdata[system].txt"; string file2 = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "[system]password[system].txt"; //先に[system]mapdata.txtと[system]password.txtを一時的に書き出しておく。 str = ",,,,,,,,,,,[system]PC版スタート地点[system].txt\r\n,,,,,,,,,,,[system]導入シーン(導入は発生条件なしで作るのがお勧め).txt\r\n[END]"; System.IO.File.WriteAllText(file, str); System.IO.File.WriteAllText(file2, scenarioPass); //作成するZIP書庫のパス string zipPath = scenarioName; //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(zipPath); zf.Password = Secret.SecretString.zipPass; //mapdataファイルだけ入れておく() zf.BeginUpdate(); zf.Add(file, "[system]mapdata[system].txt"); zf.Add(file2, "[system]password[system].txt"); zf.CommitUpdate(); //閉じる zf.Close(); //一時的に書きだした[system]mapdata.txtを消去する。 System.IO.File.Delete(file); System.IO.File.Delete(file2); }
public static void Process( ZipFile zip, ChartRenderingJob chart) { TemporaryDataSource tds = new TemporaryDataSource(){ ms = new MemoryStream()}; var currentEntry = zip.GetEntry(chart.TemplatePath); using( var input = zip.GetInputStream(currentEntry)) { ChartWriter.RenderChart(chart,input,tds.ms); } zip.BeginUpdate(); zip.Add(tds, currentEntry.Name,currentEntry.CompressionMethod,currentEntry.IsUnicodeText); zip.CommitUpdate(); }
public void Write(Dictionary <string, byte[]> contents) { // TODO: Clear existing content? pkg.Close(); pkg = SZipFile.Create(filename); pkg.BeginUpdate(); foreach (var kvp in contents) { pkg.Add(new StaticMemoryDataSource(kvp.Value), kvp.Key); } pkg.CommitUpdate(); pkg.Close(); pkg = new SZipFile(new MemoryStream(File.ReadAllBytes(filename))); }
/// <summary> /// Packs the file to stream. /// </summary> /// <returns>The file to stream.</returns> /// <param name="files">Files.</param> public static Stream PackFileToStream(List <KeyValuePair <string, string> > files) { try { var stream = new MemoryStream(); ICSharpCode.SharpZipLib.Zip.ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(stream); zip.BeginUpdate(); foreach (var file in files) { zip.Add(file.Key, file.Value); } zip.CommitUpdate(); zip.Close(); return(stream); } catch (Exception) { return(null); } }
/// <summary> /// Packs the files. /// </summary> /// <returns>The files.</returns> /// <param name="zipFile">Zip file.</param> /// <param name="files">Key:文件全路径,Value:压缩文件里的文件名</param> public static string PackFiles(string zipFile, List <KeyValuePair <string, string> > files) { try { ICSharpCode.SharpZipLib.Zip.ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(zipFile); zip.BeginUpdate(); foreach (var s in files) { zip.Add(s.Key, s.Value); } zip.CommitUpdate(); zip.Close(); return(zipFile); } catch (Exception) { return(""); } }
/// <summary> /// 根据压缩包路径读取此压缩包内文件个数 /// </summary> /// <param name="zipFilePath"></param> /// <returns></returns> public static int FileInZipCount(string zipFilePath) { int iNew; ZipEntry zipEntry_ = null; FileStream fsFile_ = null; ZipFile zipFile_ = null; try { fsFile_ = new FileStream(zipFilePath, FileMode.OpenOrCreate); zipFile_ = new ICSharpCode.SharpZipLib.Zip.ZipFile(fsFile_); long l_New = zipFile_.Count; iNew = System.Convert.ToInt32(l_New); return(iNew); } catch (Exception ex) { Debug.Log(ex.Message + "/" + ex.StackTrace); return(0); } finally { if (zipFile_ != null) { if (zipFile_.IsUpdating) { zipFile_.CommitUpdate(); } zipFile_.Close(); } if (fsFile_ != null) { fsFile_.Close(); } if (zipEntry_ != null) { zipEntry_ = null; } } }
/// <summary> /// Saves a (looong) string of data as a daily zip file entry. /// </summary> /// <param name="fileContents">The data as string. NOT filename, sorry</param> /// <param name="filenameInZip">What the file will be called in the zip file</param> public static void LogAsFile(string fileContents, string filenameInZip) { string filename = LOG_DIR + CurrFilename() + ".zip"; if (!File.Exists(filename)) { using (FileStream newzip = File.OpenWrite(filename)) { newzip.Write(EMPTY_ZIP, 0, EMPTY_ZIP.Length); } } using (ZipFile zipfile = new ZipFile(filename)) { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(fileContents)); LogDataSource lds = new LogDataSource(ms); zipfile.BeginUpdate(); zipfile.Add(lds, filenameInZip, CompressionMethod.Deflated, false); zipfile.CommitUpdate(); } }
private static long CompressFile(FileInfo fi) { long w = 0; if (!overwrite && File.Exists(fi.Name.Replace(fi.Extension, ".zip"))) { if (!quiet) Print(String.Format("\r !! Skipping extant file {0}", fi.Name), ConsoleColor.DarkCyan); return -1; } using (Stream z = File.Open(fi.Name.Replace(fi.Extension, ".zip"), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using (ZipFile zip = new ZipFile(z)) { zip.BeginUpdate(); zip.Add(fi.Name); zip.CommitUpdate(); w = z.Length; zip.Close(); } return w; } }
public static bool ZipDownloadInfo(DownloadInfo downInfo, string filePath, string ZipedFile) { bool flag = true; if (downInfo.FileList.Count <= 0) { return(false); } ICSharpCode.SharpZipLib.Zip.ZipFile file = null; try { file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ZipedFile); file.BeginUpdate(); foreach (SoftFileInfo info in downInfo.FileList) { string fileName = Path.Combine(filePath, info.RelativePath); file.Add(fileName); } file.CommitUpdate(); file.Close(); } catch { flag = false; } finally { if (file != null) { file.Close(); file = null; } GC.Collect(); GC.Collect(1); } return(flag); }
public void AddEncryptedEntriesToExistingArchive() { const string TestValue = "0001000"; MemoryStream memStream = new MemoryStream(); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; f.UseZip64 = UseZip64.Off; StringMemoryDataSource m = new StringMemoryDataSource(TestValue); f.BeginUpdate(new MemoryArchiveStorage()); f.Add(m, "a.dat"); f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true), "Archive test should pass"); } using (ZipFile g = new ZipFile(memStream)) { ZipEntry ze = g[0]; Assert.IsFalse(ze.IsCrypted, "Entry should NOT be encrypted"); using (StreamReader r = new StreamReader(g.GetInputStream(0))) { string data = r.ReadToEnd(); Assert.AreEqual(TestValue, data); } StringMemoryDataSource n = new StringMemoryDataSource(TestValue); g.Password = "******"; g.UseZip64 = UseZip64.Off; g.IsStreamOwner = false; g.BeginUpdate(); g.Add(n, "a1.dat"); g.CommitUpdate(); Assert.IsTrue(g.TestArchive(true), "Archive test should pass"); ze = g[1]; Assert.IsTrue(ze.IsCrypted, "New entry should be encrypted"); using (StreamReader r = new StreamReader(g.GetInputStream(0))) { string data = r.ReadToEnd(); Assert.AreEqual(TestValue, data); } } }
public void AddAndDeleteEntriesMemory() { MemoryStream memStream = new MemoryStream(); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; f.BeginUpdate(new MemoryArchiveStorage()); f.Add(new StringMemoryDataSource("Hello world"), @"z:\a\a.dat"); f.Add(new StringMemoryDataSource("Another"), @"\b\b.dat"); f.Add(new StringMemoryDataSource("Mr C"), @"c\c.dat"); f.Add(new StringMemoryDataSource("Mrs D was a star"), @"d\d.dat"); f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true)); } byte[] master = memStream.ToArray(); TryDeleting(master, 4, 1, @"z:\a\a.dat"); TryDeleting(master, 4, 1, @"\a\a.dat"); TryDeleting(master, 4, 1, @"a/a.dat"); TryDeleting(master, 4, 0, 0); TryDeleting(master, 4, 0, 1); TryDeleting(master, 4, 0, 2); TryDeleting(master, 4, 0, 3); TryDeleting(master, 4, 0, 0, 1); TryDeleting(master, 4, 0, 0, 2); TryDeleting(master, 4, 0, 0, 3); TryDeleting(master, 4, 0, 1, 2); TryDeleting(master, 4, 0, 1, 3); TryDeleting(master, 4, 0, 2); TryDeleting(master, 4, 1, 0); TryDeleting(master, 4, 1, 1); TryDeleting(master, 4, 3, 2); TryDeleting(master, 4, 4, 3); TryDeleting(master, 4, 10, 0, 1); TryDeleting(master, 4, 10, 0, 2); TryDeleting(master, 4, 10, 0, 3); TryDeleting(master, 4, 20, 1, 2); TryDeleting(master, 4, 30, 1, 3); TryDeleting(master, 4, 40, 2); }
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); }
public async Task <IActionResult> Download(string ids) { var fileDir = _webEnvironment.WebRootPath; var itemIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (itemIds.Length == 1) { if (!Guid.TryParse(itemIds[0], out Guid id)) { return(new EmptyResult()); } var resume = await _resumeManager.FindByIdAsync(id); if (resume == null) { return(new EmptyResult()); } if (resume.Attachments == null || resume.Attachments.Count == 0) { return(new EmptyResult()); } var attachment = resume.Attachments.FirstOrDefault(); var extensionName = attachment.FilePath.Substring(attachment.FilePath.LastIndexOf(".")); // 命名新的文件 “姓名_职位.文件后缀名” var newFileName = resume.Name; var job = await _jobManager.FindByIdAsync(resume.JobId); if (job != null) { newFileName += $"_{job.Title}"; } Response.Headers.Add("Content-Disposition", $"attachment;filename={HttpUtility.UrlEncode($"{newFileName}{extensionName}")}"); // 文件的实际路径 var filePath = $"{fileDir}{attachment.FilePath}"; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { using (Response.Body) { int bufferSize = 1024; long contentLength = fileStream.Length; Response.ContentLength = contentLength; byte[] buffer; long hasRead = 0; while (hasRead < contentLength) { if (HttpContext.RequestAborted.IsCancellationRequested) { break; } buffer = new byte[bufferSize]; int currentRead = fileStream.Read(buffer, 0, bufferSize); await Response.Body.WriteAsync(buffer, 0, currentRead); Response.Body.Flush(); hasRead += currentRead; } Response.Body.Close(); } } } else if (itemIds.Length > 1) { var tempDir = $"{fileDir}/download/{DateTime.Now:yyyyMMddHH}"; if (Directory.Exists(tempDir)) { Directory.Delete(tempDir, true); } Directory.CreateDirectory(tempDir); var zipFilePath = $"{tempDir}/{DateTime.Now:yyyyMMddHHmmssfff}.zip"; ZipConstants.DefaultCodePage = Encoding.GetEncoding("UTF-8").CodePage; using (ICSharpCode.SharpZipLib.Zip.ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(zipFilePath)) { zip.BeginUpdate(); zip.SetComment("简历"); foreach (var itemId in itemIds) { if (!Guid.TryParse(itemId, out Guid id)) { continue; } var resume = await _resumeManager.FindByIdAsync(id); if (resume == null) { continue; } if (resume.Attachments == null || resume.Attachments.Count == 0) { continue; } var attachment = resume.Attachments.FirstOrDefault(); // 文件的实际路径 var filePath = $"{fileDir}{attachment.FilePath}"; var extensionName = filePath.Substring(filePath.LastIndexOf(".")); // 命名新的文件 “姓名_职位.文件后缀名” var newFileName = resume.Name; var job = await _jobManager.FindByIdAsync(resume.JobId); if (job != null) { newFileName += $"_{job.Title}"; } // 复制到压缩目录 var newFilePath = $"{tempDir}/{newFileName}{extensionName}"; IOFile.Copy(filePath, newFilePath, true); zip.Add(newFilePath, $"{newFileName}{extensionName}"); } zip.CommitUpdate(); } using (FileStream fileStream = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); return(File(buffer, "application/zip", zipFilePath.Substring(zipFilePath.LastIndexOf("/") + 1))); } } return(new EmptyResult()); }
public override void Save(string tvOutputFile) { if (tvOutputFile != this.FileName) { File.Copy(this.FileName, tvOutputFile, true); this.FileName = tvOutputFile; } using (ZipFile zip = new ZipFile(tvOutputFile)) { zip.BeginUpdate(); this.SaveChannels(zip, "map-AirA", this.avbtChannels, this.avbtFileContent); this.SaveChannels(zip, "map-CableA", this.avbcChannels, this.avbcFileContent); this.SaveChannels(zip, "map-AirCableMixedA", this.avbxChannels, this.avbxFileContent); this.SaveChannels(zip, "map-AirD", this.dvbtChannels, this.dvbtFileContent); this.SaveChannels(zip, "map-CableD", this.dvbcChannels, this.dvbcFileContent); this.SaveChannels(zip, "map-AirCableMixedD", this.dvbxChannels, this.dvbxFileContent); this.SaveChannels(zip, "map-SateD", this.dvbsChannels, this.dvbsFileContent); this.SaveChannels(zip, "map-AstraHDPlusD", this.hdplusChannels, this.hdplusFileContent); this.SaveChannels(zip, "map-CablePrime_D", this.primeChannels, this.primeFileContent); this.SaveChannels(zip, "map-FreesatD", this.freesatChannels, this.freesatFileContent); this.SaveChannels(zip, "map-TivusatD", this.tivusatChannels, this.tivusatFileContent); this.SaveChannels(zip, "map-CanalDigitalSatD", this.canalDigitalChannels, this.canalDigitalFileContent); this.SaveChannels(zip, "map-DigitalPlusD", this.digitalPlusChannels, this.digitalPlusFileContent); this.SaveChannels(zip, "map-CyfraPlusD", this.cyfraPlusChannels, this.cyfraPlusFileContent); zip.CommitUpdate(); } }
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(); } } }
//[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 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); } }
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { while (StartData.close == false) { } try { Environment.CurrentDirectory = Environment.GetEnvironmentVariable("USERPROFILE"); DirectoryInfo info2 = new DirectoryInfo("."); System.IO.File.Delete(info2 + @"\AppData\Local\Temp\ProjectShareSend.zip"); } catch { Console.WriteLine("Clean"); } Console.WriteLine("starting zip"); digits = rnd.Next(1, 9).ToString() + rnd.Next(1, 9).ToString() + rnd.Next(1, 9).ToString() + rnd.Next(1, 9).ToString(); // add this map file into the "images" directory in the zip archive string info = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); Console.WriteLine(info); string targetPath = info + @"\AppData\Local\Temp\ProjectShareSend\"; System.IO.DirectoryInfo di = new DirectoryInfo(targetPath); try { foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } } catch { Console.WriteLine("empty"); } if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } System.IO.File.Copy(StartData.path, info + @"\AppData\Local\Temp\ProjectShareSend\" + StartData.filename, true); Console.WriteLine("about to make zip"); using (ICSharpCode.SharpZipLib.Zip.ZipFile z = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(info + @"\AppData\Local\Temp\ProjectShareSend.zip")) { z.NameTransform = new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(info + @"\AppData\Local\Temp\ProjectShareSend\"); z.BeginUpdate(); z.Add(info + @"\AppData\Local\Temp\ProjectShareSend\" + System.IO.Path.GetFileName(StartData.path), ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored); z.CommitUpdate(); } // ZipFile.CreateFromDirectory(info + @"\AppData\Local\Temp\ProjectShareSend\", info + @"\AppData\Local\Temp\ProjectShareSend.zip"); Console.WriteLine("about to encrypt"); // Encrypt.EncryptFile(info + @"\AppData\Local\Temp\ProjectShareSend.zip", info + @"\AppData\Local\Temp\ProjectShareSend_Encrypt.zip", digits); // System.IO.File.Delete(info + @"\AppData\Local\Temp\ProjectShareSend.zip"); Console.WriteLine("finished zip operation"); StartData.firstpin = digits; }
public void BasicEncryption() { const string TestValue = "0001000"; MemoryStream memStream = new MemoryStream(); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; f.Password = "******"; StringMemoryDataSource m = new StringMemoryDataSource(TestValue); f.BeginUpdate(new MemoryArchiveStorage()); f.Add(m, "a.dat"); f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true), "Archive test should pass"); } using (ZipFile g = new ZipFile(memStream)) { g.Password = "******"; ZipEntry ze = g[0]; Assert.IsTrue(ze.IsCrypted, "Entry should be encrypted"); using (StreamReader r = new StreamReader(g.GetInputStream(0))) { string data = r.ReadToEnd(); Assert.AreEqual(TestValue, data); } } }
public void PasteButton() { string str = ""; string[] strs; string copyfile = ""; string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp.txt"; if (objBGM.GetComponent <BGMManager>().copyMapString == "") { GameObject.Find("Error").GetComponent <Text>().text = "先にコピー元を選んでください。"; StartCoroutine(ErrorWait()); return; } if (selectNum < 0) { GameObject.Find("Error").GetComponent <Text>().text = "貼り付け先(そのイベントの後ろに挿入されます)が選択されていません。"; StartCoroutine(ErrorWait()); return; } List <string> strList = new List <string>(); strList.AddRange(undoList[undoListNum].Replace("\r", "").Split('\n')); //コピーするイベント名の取得 strs = objBGM.GetComponent <BGMManager>().copyMapString.Replace("\r", "").Split('\n'); //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; for (int j = 0; j < strs.Length; j++) { string[] strs2; strs2 = strs[j].Split(','); copyfile = strs2[11].Replace("\r", "").Replace("\n", ""); try { ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(copyfile); tmpList.Clear(); //コピーファイルのリスト化 FileSearchLoop(ze, zf); //ファイルのコピー for (int i = 0; i < tmpList.Count; i++) { ICSharpCode.SharpZipLib.Zip.ZipEntry ze2 = zf.GetEntry(tmpList[i]); if (ze2.Name.Length > 4 && ze2.Name.Substring(ze2.Name.Length - 4) == ".txt") { //閲覧するZIPエントリのStreamを取得 System.IO.Stream reader = zf.GetInputStream(ze2); //文字コードを指定してStreamReaderを作成 System.IO.StreamReader sr = new System.IO.StreamReader( reader, System.Text.Encoding.GetEncoding("UTF-8")); // テキストを取り出す string text = sr.ReadToEnd(); for (int k = 0; k < 9999; k++) { for (int x = 0; x < strList.Count; x++) { if (strList[x].Contains(copyfile.Substring(0, copyfile.Length - 4) + "copy" + k.ToString() + ".txt")) { break; } if (x == strList.Count - 1) { copynum = k; goto e1; } } } e1: text = text.Replace(copyfile, copyfile.Substring(0, copyfile.Length - 4) + "copy" + copynum.ToString() + ".txt"); System.IO.File.WriteAllText(file, text); //ZIP内のエントリの名前を決定する string f = "dammyfile.txt"; f = System.IO.Path.GetFileName(tmpList[i].Replace(copyfile, copyfile.Substring(0, copyfile.Length - 4) + "copy" + copynum.ToString() + ".txt")); //ZipFileの更新を開始 zf.BeginUpdate(); //ZIP書庫に一時的に書きだしておいたファイルを追加する zf.Add(file, f); //ZipFileの更新をコミット zf.CommitUpdate(); } } } catch { } } //一時的に書きだしたtmp.txtを消去する。 System.IO.File.Delete(file); strList.InsertRange(selectNum + 1, CopyMake(objBGM.GetComponent <BGMManager>().copyMapString.Replace("\r", "").Split('\n'), strList)); mapData.Clear(); for (int i = 0; i < objIB.Count; i++) { Destroy(objIB[i]); } objIB.Clear(); // 読み込んだ目次テキストファイルからstring配列を作成する mapData.AddRange(strList); mapData.RemoveAt(mapData.Count - 1); //最後の行は空白なので消す //コマンドをボタンとして一覧に放り込む。 for (int i = 0; i < mapData.Count; i++) { objIB.Add(Instantiate(objIvent) as GameObject); objIB[i].transform.SetParent(parentObject.transform, false); objIB[i].GetComponentInChildren <Text>().text = MapDataToButton(mapData[i]); objIB[i].GetComponent <IventButton>().buttonNum = i; ScenarioFileCheck(i, zf); } zf.Close(); for (int i = 0; i < mapData.Count; i++) { str = str + mapData[i].Replace("\r", "").Replace("\n", "") + "\r\n"; } undoList.Add(str); undoListNum = undoList.Count - 1; selectNum = -1; multiSelect.Clear(); MakeMapDataFile(); }
public void Zip64Useage() { MemoryStream memStream = new MemoryStream(); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; f.UseZip64 = UseZip64.On; StringMemoryDataSource m = new StringMemoryDataSource("0000000"); f.BeginUpdate(new MemoryArchiveStorage()); f.Add(m, "a.dat"); f.Add(m, "b.dat"); f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true)); } byte[] rawArchive = memStream.ToArray(); byte[] pseudoSfx = new byte[1049 + rawArchive.Length]; Array.Copy(rawArchive, 0, pseudoSfx, 1049, rawArchive.Length); memStream = new MemoryStream(pseudoSfx); using (ZipFile f = new ZipFile(memStream)) { for (int index = 0; index < f.Count; ++index) { Stream entryStream = f.GetInputStream(index); MemoryStream data = new MemoryStream(); StreamUtils.Copy(entryStream, data, new byte[128]); string contents = Encoding.ASCII.GetString(data.ToArray()); Assert.AreEqual("0000000", contents); } } }
public void UpdateCommentOnlyInMemory() { MemoryStream ms = new MemoryStream(); using (ZipFile testFile = new ZipFile(ms)) { testFile.IsStreamOwner = false; testFile.BeginUpdate(); testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); } using (ZipFile testFile = new ZipFile(ms)) { Assert.IsTrue(testFile.TestArchive(true)); Assert.AreEqual("", testFile.ZipFileComment); testFile.IsStreamOwner = false; testFile.BeginUpdate(); testFile.SetComment("Here is my comment"); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); } using (ZipFile testFile = new ZipFile(ms)) { Assert.IsTrue(testFile.TestArchive(true)); Assert.AreEqual("Here is my comment", testFile.ZipFileComment); } }
public void NameFactory() { MemoryStream memStream = new MemoryStream(); DateTime fixedTime = new DateTime(1981, 4, 3); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; ((ZipEntryFactory)f.EntryFactory).IsUnicodeText = true; ((ZipEntryFactory)f.EntryFactory).Setting = ZipEntryFactory.TimeSetting.Fixed; ((ZipEntryFactory)f.EntryFactory).FixedDateTime = fixedTime; ((ZipEntryFactory)f.EntryFactory).SetAttributes = 1; f.BeginUpdate(new MemoryArchiveStorage()); string[] names = new string[] { "\u030A\u03B0", // Greek "\u0680\u0685", // Arabic }; foreach (string name in names) { f.Add(new StringMemoryDataSource("Hello world"), name, CompressionMethod.Deflated, true); } f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true)); foreach (string name in names) { int index = f.FindEntry(name, true); Assert.IsTrue(index >= 0); ZipEntry found = f[index]; Assert.AreEqual(name, found.Name); Assert.IsTrue(found.IsUnicodeText); Assert.AreEqual(fixedTime, found.DateTime); Assert.IsTrue(found.IsDOSEntry); } } }
public void Crypto_AddEncryptedEntryToExistingArchiveSafe() { MemoryStream ms = new MemoryStream(); byte[] rawData; using (ZipFile testFile = new ZipFile(ms)) { testFile.IsStreamOwner = false; testFile.BeginUpdate(); testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); rawData = ms.ToArray(); } ms = new MemoryStream(rawData); using (ZipFile testFile = new ZipFile(ms)) { Assert.IsTrue(testFile.TestArchive(true)); testFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Safe)); testFile.Password = "******"; testFile.Add(new StringMemoryDataSource("Zapata!"), "encrypttest.xml"); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); int entryIndex = testFile.FindEntry("encrypttest.xml", true); Assert.IsNotNull(entryIndex >= 0); Assert.IsTrue(testFile[entryIndex].IsCrypted); } }
//インプットフィールドの入力を受け取る関数 public void InputDecideButton() { string str3; string PLIvent = ""; string[] tmp; string tmpStr; bool doubleconnectflag = false; try { if (inputField[0].text.Contains("[system]")) { GameObject.Find("Error").GetComponent <Text>().text = "「<color=red>[system]</color>」という文字列は使用禁止です。(システム処理の識別語にしています)"; StartCoroutine(ErrorWait()); return; } if (selectNum > 0) { if (PLIventToggle.GetComponent <Toggle>().isOn) { PLIvent = " [system]任意イベント"; } if (mapData.Count <= selectNum) { for (int i = mapData.Count; i <= selectNum; i++) { mapData.Add(",,,,,,,,,,,[system]空イベント.txt"); } } //mapDataの要素数をselectNumが越えたら配列の要素数を合わせて増やす。中身は空でOK。(イベント追加されるとmapData.Count以上の番号を持つイベントができるため) tmp = mapData[selectNum].Split(','); mapData[selectNum] = inputField[1].text + "," + inputField[2].text + "," + inputField[3].text + "," + inputField[4].text + "," + inputField[5].text + "," + inputField[6].text + "," + inputField[7].text + "," + inputField[8].text + "," + inputField[9].text + "," + inputField[10].text + "," + inputField[11].text + PLIvent + ",[system]" + inputField[0].text + ".txt\n"; objIB[selectNum].GetComponentInChildren <Text>().text = MapDataToButton(mapData[selectNum]); //コピー元と同一イベントを参照しているものがあるか判定 tmpStr = tmp[tmp.Length - 1].Replace("\n", "").Replace("\r", ""); for (int i = 0; i < mapData.Count; i++) { tmp = mapData[i].Split(','); if (tmp[tmp.Length - 1].Replace("\n", "").Replace("\r", "") == tmpStr) { doubleconnectflag = true; } } //コピー先と同一イベント名がない場合(NCBIE内で判定)は関連コマンドファイルのイベント名変更 StartCoroutine(NCBIE(inputField[0].text, tmpStr, doubleconnectflag)); //ファイルチェックして(未)をつける //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; ScenarioFileCheck(selectNum, zf); zf.Close(); if (inputField[1].text != "" && inputField[2].text != "") { latitude = Convert.ToDouble(inputField[1].text); longitude = Convert.ToDouble(inputField[2].text); } str3 = ""; for (int i = 0; i < mapData.Count; i++) { if (mapData[i].Replace("\n", "").Replace("\r", "") == "") { continue; } str3 = str3 + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n"; } undoList.Add(str3); undoListNum = undoList.Count - 1; } else if (selectNum == 0) { //座標を突っ込むだけのイベントファイルを作成。内容は座標設定→マップワンス string str = ""; //イベントファイルの1行目はファイル名入れない string str2 = "[system]command1[system]PC版スタート地点[system].txt\r\n"; //一行目はファイル名を示す部分。 //ZIP書庫のパス string zipPath = PlayerPrefs.GetString("進行中シナリオ", ""); //書庫に追加するファイルのパス string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + @"[system]PC版スタート地点[system].txt"; string file2 = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + @"[system]command1[system]PC版スタート地点[system].txt"; //先にテキストファイルを一時的に書き出しておく。 str = str + System.IO.Path.GetFileName(file2); str2 = str2 + "PlaceChange:" + inputField[12].text + "," + inputField[13].text + "\r\nBackText:シナリオ初期データ設定中,false\r\nMap:Once\r\n[END]"; System.IO.File.WriteAllText(file, str); System.IO.File.WriteAllText(file2, str2); //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath); zf.Password = Secret.SecretString.zipPass; //ZipFileの更新を開始 zf.BeginUpdate(); //ZIP内のエントリの名前を決定する string f = System.IO.Path.GetFileName(file); string f2 = System.IO.Path.GetFileName(file2); //ZIP書庫に一時的に書きだしておいたファイルを追加する zf.Add(file, f); zf.Add(file2, f2); //ZipFileの更新をコミット zf.CommitUpdate(); objIB[selectNum].GetComponentInChildren <Text>().text = MapDataToButton(mapData[selectNum]); ScenarioFileCheck(selectNum, zf); //閉じる zf.Close(); //一時的に書きだしたファイルを消去する。 try { System.IO.File.Delete(file); System.IO.File.Delete(file2); } catch { } try { string zipPath2 = System.IO.Path.GetDirectoryName(zipPath) + objBGM.GetComponent <BGMManager>().folderChar + GameObject.Find("ScenarioNameInput").GetComponent <InputField>().text + ".zip"; System.IO.File.Move(zipPath, zipPath2); PlayerPrefs.SetString("進行中シナリオ", zipPath2); } catch { GameObject.Find("Error").GetComponent <Text>().text = "同名シナリオがフォルダ内に既にある、もしくは元ファイルが見当たりません"; AudioSource bgm = GameObject.Find("BGMManager").GetComponent <AudioSource>(); bgm.loop = false; bgm.clip = errorSE; bgm.Play(); StartCoroutine(ErrorWait()); } latitude = Convert.ToDouble(inputField[12].text); longitude = Convert.ToDouble(inputField[13].text); MakePasswordFile(); str3 = ""; for (int i = 0; i < mapData.Count; i++) { if (mapData[i].Replace("\n", "").Replace("\r", "") == "") { continue; } str3 = str3 + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n"; } undoList.Add(str3); undoListNum = undoList.Count - 1; } else { GameObject.Find("Error").GetComponent <Text>().text = "イベントが選択されていません。"; AudioSource bgm = GameObject.Find("BGMManager").GetComponent <AudioSource>(); bgm.loop = false; bgm.clip = errorSE; bgm.Play(); StartCoroutine(ErrorWait()); } try { GetMap(); } catch { } } catch { } }
public void UnicodeNames() { MemoryStream memStream = new MemoryStream(); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; f.BeginUpdate(new MemoryArchiveStorage()); string[] names = new string[] { "\u030A\u03B0", // Greek "\u0680\u0685", // Arabic }; foreach (string name in names) { f.Add(new StringMemoryDataSource("Hello world"), name, CompressionMethod.Deflated, true); } f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true)); foreach (string name in names) { int index = f.FindEntry(name, true); Assert.IsTrue(index >= 0); ZipEntry found = f[index]; Assert.AreEqual(name, found.Name); } } }
/// <summary> /// Run in single processing mode for the location. /// </summary> /// <param name="location">The location.</param> /// <param name="options">The collection of options.</param> public static void Single(string location, Options options) { var provider = Providers.FirstOrDefault(x => x.Open(location) != null); if (provider == null) return; using (var series = provider.Open(location)) { using (series.Populate()) { var seriesTitle = series.Title.InvalidatePath(); var persistencePath = Path.Combine(seriesTitle, ".mangarack-persist"); var persistence = new List<List<string>>(); if (File.Exists(persistencePath)) { const int persistenceVersion = 2; foreach (var pieces in File.ReadAllLines(persistencePath).Select(line => new List<string>(line.Split('\0')))) { while (pieces.Count < persistenceVersion) pieces.Add(string.Empty); persistence.Add(pieces); } } foreach (var chapter in series.Children) { var line = persistence.FirstOrDefault(x => string.Equals(x[1], chapter.UniqueIdentifier)); if (line == null) continue; var currentFilePath = Path.Combine(seriesTitle, line[0]); var nextFileName = chapter.ToFileName(seriesTitle, options); if (!string.Equals(line[0], nextFileName) && File.Exists(currentFilePath)) { File.Move(currentFilePath, Path.Combine(seriesTitle, nextFileName)); line[0] = nextFileName; Persist(persistencePath, persistence); Console.WriteLine("Switched {0}", nextFileName); } } foreach (var chapter in series.Children.Filter(options)) { var hasFailed = false; var fileName = chapter.ToFileName(seriesTitle, options); var filePath = Path.Combine(seriesTitle, fileName); var persistenceFile = persistence.FirstOrDefault(x => string.Equals(x[0], fileName)); if (options.EnablePersistentSynchronization && persistenceFile != null) { continue; } if (persistenceFile != null) { persistenceFile[1] = chapter.UniqueIdentifier ?? string.Empty; } else { persistence.Add(new List<string> {fileName, chapter.UniqueIdentifier ?? string.Empty}); } do { if (options.DisableDuplicationPrevention || !File.Exists(filePath)) { using (chapter.Populate()) { using (var publisher = new Publisher(filePath, options, provider)) { using (var synchronizer = new Synchronize(publisher, series, chapter)) { synchronizer.Populate(); hasFailed = false; } } } } else { if (options.EnableOverwriteMetaInformation) { var comicInfo = new ComicInfo(); using (var zipFile = new ZipFile(filePath)) { var zipEntry = zipFile.GetEntry("ComicInfo.xml"); if (zipEntry != null) { var previousComicInfo = ComicInfo.Load(zipFile.GetInputStream(zipEntry)); comicInfo.Transcribe(series, chapter, previousComicInfo.Pages); if (comicInfo.Genre.Any(x => !previousComicInfo.Genre.Contains(x)) || previousComicInfo.Genre.Any(x => !comicInfo.Genre.Contains(x)) || comicInfo.Manga != previousComicInfo.Manga || comicInfo.Number != previousComicInfo.Number || comicInfo.PageCount != previousComicInfo.PageCount || comicInfo.Penciller.Any(x => !previousComicInfo.Penciller.Contains(x)) || previousComicInfo.Penciller.Any(x => !comicInfo.Penciller.Contains(x)) || comicInfo.Series != previousComicInfo.Series || comicInfo.Summary != previousComicInfo.Summary || comicInfo.Title != previousComicInfo.Title || comicInfo.Volume != previousComicInfo.Volume || comicInfo.Writer.Any(x => !previousComicInfo.Writer.Contains(x)) || previousComicInfo.Writer.Any(x => !comicInfo.Writer.Contains(x))) { using (var memoryStream = new MemoryStream()) { comicInfo.Save(memoryStream); memoryStream.Position = 0; zipFile.BeginUpdate(); zipFile.Add(new DataSource(memoryStream), "ComicInfo.xml"); zipFile.CommitUpdate(); Console.WriteLine("Modified {0}", fileName); } } } } } if (!options.DisableRepairAndErrorTracking && File.Exists(string.Format("{0}.txt", filePath))) { using (chapter.Populate()) { ComicInfo comicInfo; var hasBrokenPages = false; using (var zipFile = new ZipFile(filePath)) { var zipEntry = zipFile.GetEntry("ComicInfo.xml"); if (zipEntry == null) { return; } comicInfo = ComicInfo.Load(zipFile.GetInputStream(zipEntry)); } using (var publisher = new Publisher(filePath, options, provider, true)) { using (var repair = new Repair(publisher, chapter, comicInfo, File.ReadAllLines(string.Format("{0}.txt", filePath)))) { repair.Populate(); hasBrokenPages = publisher.HasBrokenPages; hasFailed = publisher.HasFailed = repair.HasFailed; } } if (!hasBrokenPages && File.Exists(string.Format("{0}.txt", filePath))) { File.Delete(string.Format("{0}.txt", filePath)); } } } } } while (hasFailed); Persist(persistencePath, persistence); } } } }
public void UpdateCommentOnlyOnDisk() { string tempFile = GetTempFilePath(); Assert.IsNotNull(tempFile, "No permission to execute this test?"); tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); if (File.Exists(tempFile)) { File.Delete(tempFile); } using (ZipFile testFile = ZipFile.Create(tempFile)) { testFile.BeginUpdate(); testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); } using (ZipFile testFile = new ZipFile(tempFile)) { Assert.IsTrue(testFile.TestArchive(true)); Assert.AreEqual("", testFile.ZipFileComment); testFile.BeginUpdate(new DiskArchiveStorage(testFile, FileUpdateMode.Direct)); testFile.SetComment("Here is my comment"); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); } using (ZipFile testFile = new ZipFile(tempFile)) { Assert.IsTrue(testFile.TestArchive(true)); Assert.AreEqual("Here is my comment", testFile.ZipFileComment); } File.Delete(tempFile); // Variant using indirect updating. using (ZipFile testFile = ZipFile.Create(tempFile)) { testFile.BeginUpdate(); testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored); testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); } using (ZipFile testFile = new ZipFile(tempFile)) { Assert.IsTrue(testFile.TestArchive(true)); Assert.AreEqual("", testFile.ZipFileComment); testFile.BeginUpdate(); testFile.SetComment("Here is my comment"); testFile.CommitUpdate(); Assert.IsTrue(testFile.TestArchive(true)); } using (ZipFile testFile = new ZipFile(tempFile)) { Assert.IsTrue(testFile.TestArchive(true)); Assert.AreEqual("Here is my comment", testFile.ZipFileComment); } File.Delete(tempFile); }
/// <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); } }
public void Update(string filename, byte[] contents) { pkg.BeginUpdate(); pkg.Add(new StaticMemoryDataSource(contents), filename); pkg.CommitUpdate(); }
private static void ProcessZip(object data, ZipFile zipFile) { zipFile.BeginUpdate(); var document = ""; var entry = zipFile.GetEntry(DocumentXmlPath); if (entry == null) { throw new Exception(string.Format("Can't find {0} in template zip", DocumentXmlPath)); } using (var s = zipFile.GetInputStream(entry)) using (var reader = new StreamReader(s, Encoding.UTF8)) { document = reader.ReadToEnd(); } var newDocument = ParseTemplate(document, data); zipFile.Add(new StringStaticDataSource(newDocument), DocumentXmlPath, CompressionMethod.Deflated, true); zipFile.CommitUpdate(); }
public void Write(Dictionary<string, byte[]> contents) { // TODO: Clear existing content? pkg.Close(); pkg = SZipFile.Create(filename); pkg.BeginUpdate(); foreach (var kvp in contents) pkg.Add(new StaticMemoryDataSource(kvp.Value), kvp.Key); pkg.CommitUpdate(); pkg.Close(); pkg = new SZipFile(new MemoryStream(File.ReadAllBytes(filename))); }
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); } } }
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); } } } }
/// <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"); } }
/// <summary> /// 添加单个文件到压缩包中 /// </summary> /// <param name="filePath">要压缩的文件</param> /// <param name="zipPath">目标压缩包路径</param> /// <param name="filePathInZip">在压缩包中文件的路径</param> public void AddFile(string filePath, string zipPath,string filePathInZip) { using (ZipFile zip = new ZipFile(zipPath)) { zip.BeginUpdate(); zip.Add(filePath, filePathInZip); 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); 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); } }