/// <summary> /// Iterate thru all the filesysteminfo objects and add it to our zip file /// </summary> /// <param name="fileSystemInfosToZip">a collection of files/directores</param> /// <param name="z">our existing ZipFile object</param> private static void GetFilesToZip(FileSystemInfo[] fileSystemInfosToZip, ZipFile z) { //check whether the objects are null if (fileSystemInfosToZip != null && z != null) { //iterate thru all the filesystem info objects foreach (FileSystemInfo fi in fileSystemInfosToZip) { //check if it is a directory if (fi is DirectoryInfo) { DirectoryInfo di = (DirectoryInfo)fi; //add the directory z.AddDirectory(di.FullName); //drill thru the directory to get all //the files and folders inside it. GetFilesToZip(di.GetFileSystemInfos(), z); } else { //add it z.Add(fi.FullName); } } } }
public static void ExtractZipFile(string archiveFilenameIn, string outFolder, Func<ZipEntry, String, bool> entryCheckFunc, string password = null) { ZipFile zf = null; try { FileStream fs = File.OpenRead(archiveFilenameIn); zf = new ZipFile(fs); if (!String.IsNullOrEmpty(password)) { zf.Password = password; // AES encrypted entries are handled automatically } foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } String entryFileName = zipEntry.Name; // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. // The unpacked length is available in the zipEntry.Size property. // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine(outFolder, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (entryCheckFunc(zipEntry, fullZipToPath)) continue; if (directoryName.Length > 0) Directory.CreateDirectory(directoryName); byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } catch (Exception ex) { throw new Exception("ExtractZipFile failed", ex); } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } }
private void ExecUnzip(Session session) { foreach (UnzipCatalog ctlg in catalogs_) { session.Log($"Extracting ZIP archive '{ctlg.ZipFile}' to folder '{ctlg.TargetFolder}"); if (!File.Exists(ctlg.ZipFile)) { session.Log($"ZIP archive does not exist: {ctlg.ZipFile}"); continue; } if (!Directory.Exists(ctlg.TargetFolder)) { Directory.CreateDirectory(ctlg.TargetFolder); } using (FileStream fs = File.OpenRead(ctlg.ZipFile)) { using (ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs)) { foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; // Ignore directories } String entryFileName = zipEntry.Name; byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); String fullZipToPath = Path.Combine(ctlg.TargetFolder, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } if (File.Exists(fullZipToPath)) { if ((ctlg.Flags & UnzipFlags.Overwrite) != UnzipFlags.Overwrite) { session.Log($"Skipping existing file '{fullZipToPath}'"); continue; } session.Log($"Overwriting existing file '{fullZipToPath}'"); File.SetAttributes(fullZipToPath, System.IO.FileAttributes.Normal); File.Delete(fullZipToPath); } using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } } } }
public ExtendedData(string fileName, string mimeType, ZipFile zipFile, ZipEntry extendedZipEntry) { FileName = fileName; MimeType = mimeType; _ExtendedZipEntry = extendedZipEntry; _ZipFile = zipFile; }
private Subtitles ProcessSubUrl(string subUrl) { var subresult = new WebClientEx().DownloadStringIgnoreAndLog(_root + subUrl); if (string.IsNullOrWhiteSpace(subresult)) return null; try { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(subresult); var href = _root + doc.DocumentNode.SelectSingleNode("//a[@class='button big download']").Attributes["href"].Value; var name = doc.DocumentNode.SelectSingleNode("//fieldset/legend[text()='Release']/../p/a").InnerText; var data = new WebClientEx().DownloadDataIgnoreAndLog(href); var outputStream = new MemoryStream(); using (var zf = new ZipFile(new MemoryStream(data))) { var ze = zf[0]; zf.GetInputStream(ze).CopyTo(outputStream); } return new Subtitles() { Title = name, File = outputStream.ToArray() }; } catch (Exception ex) { _logger.WarnException("Error getting subtitle "+subUrl,ex); } return null; }
public static string GetFirstZipEntryWithEnding(string zipfile, string ending) { #if SHARPZIPLIB if (string.IsNullOrEmpty(zipfile)) return null; ZipFile zf = null; try { zf = new ZipFile(zipfile); } catch (Exception) { return null; } string name = null; foreach (ZipEntry zipEntry in zf) { if (zipEntry.Name.ToLower().EndsWith(ending)) { name = zipEntry.Name; break; } } zf.Close(); return name; #else return null; #endif }
private static void CreateCatalogs(string[] files) { foreach (string file in files) { Stream filestream = File.OpenRead(file); ZipFile zfile = new ZipFile(filestream); foreach (ZipEntry entry in zfile) { if (entry.Name == "catalog.xml") { Stream stream = zfile.GetInputStream(entry); byte[] data = new byte[entry.Size]; int length = stream.Read(data, 0, (int)entry.Size); string src = UTF8Encoding.UTF8.GetString(data); if (src.IndexOf("<components>") > 0) { src = Regex.Replace(src, "\\s*<libraries>.*</libraries>", "", RegexOptions.Singleline); src = Regex.Replace(src, "\\s*<features>.*</features>", "", RegexOptions.Singleline); src = Regex.Replace(src, "\\s*<files>.*</files>", "", RegexOptions.Singleline); src = Regex.Replace(src, "icon=\"[^\"]+\"\\s*", ""); File.WriteAllText("catalogs\\" + Path.GetFileNameWithoutExtension(file) + "_catalog.xml", src); } } } } }
/// <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(); }
void Work() { try { ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(m_ZipFilePath); m_FileTotalCount = zipFile.Count; zipFile.Close(); FastZipEvents zipEvent = new FastZipEvents(); zipEvent.Progress = OnProcess; zipEvent.CompletedFile = OnCompletedFile; FastZip fastZip = new FastZip(zipEvent); fastZip.CreateEmptyDirectories = true; fastZip.ExtractZip(m_ZipFilePath, m_OutDirPath, null); m_IsFinish = true; } catch (Exception exception) { //Log.e(exception.Message); m_ErrorMsg = exception.Message; m_IsError = true; m_IsFinish = true; } }
private void setDbfInfoFromZip(string dbfPath) { try { //Navigate the Zip to find the files and update their index ZipFile zFile = new ZipFile(dbfPath); foreach (ZipEntry ze in zFile) { if(ze.Name.ToLower().EndsWith(".dbf")) { //Extracts the file in temp FastZip fz = new FastZip(); fz.ExtractZip(dbfPath, Path.GetTempPath(), ICSharpCode.SharpZipLib.Zip.FastZip.Overwrite.Always,null,"",""); setDbfInfo(Path.Combine(Path.GetTempPath(),ze.Name)); } } } catch { return; } //TODO: read the sbf data into the datagrid //DataTable dt=getInfoFromDBF(dbfPath); //dataGrid1.DataSource=dt; //dataGrid1.CaptionText=dbfPath; }
static void ListZipFile(string fileName, string fileFilter, string directoryFilter) { using (ZipFile zipFile = new ZipFile(fileName)) { PathFilter localFileFilter = new PathFilter(fileFilter); PathFilter localDirFilter = new PathFilter(directoryFilter); if ( zipFile.Count == 0 ) { Console.WriteLine("No entries to list"); } else { for ( int i = 0 ; i < zipFile.Count; ++i) { ZipEntry e = zipFile[i]; if ( e.IsFile ) { string path = Path.GetDirectoryName(e.Name); if ( localDirFilter.IsMatch(path) ) { if ( localFileFilter.IsMatch(Path.GetFileName(e.Name)) ) { Console.WriteLine(e.Name); } } } else if ( e.IsDirectory ) { if ( localDirFilter.IsMatch(e.Name) ) { Console.WriteLine(e.Name); } } else { Console.WriteLine(e.Name); } } } } }
public static bool AddToCbz(string fileName, string zipFileName) { if (Path.GetExtension (zipFileName).Length == 0) { zipFileName = Path.ChangeExtension (zipFileName, ".zip"); } ZipFile zipFile; try { if (File.Exists (zipFileName)) { zipFile = new ZipFile (zipFileName); } else { zipFile = ZipFile.Create (zipFileName); } using (zipFile) { zipFile.UseZip64 = UseZip64.Off; zipFile.BeginUpdate (); zipFile.Add (Path.GetFullPath (fileName)); zipFile.CommitUpdate (); return true; } } catch { return false; } }
public void Convert(EndianBinaryWriter writer) { var jbtWriter = new JbtWriter(writer); var zf = new ZipFile(jarFile); foreach (ZipEntry ze in zf) { if (!ze.IsFile) continue; if (!ze.Name.EndsWith(".class")) continue; var type = new CompileTypeInfo(); type.Read(zf.GetInputStream(ze)); var reader = new BinaryReader(zf.GetInputStream(ze)); var buffer = new byte[ze.Size]; reader.Read(buffer, 0, (int)ze.Size); jbtWriter.Write(type.Name, buffer); } jbtWriter.Flush(); }
public static void UnzipTo(string filename, Stream toStream) { ZipFile zf = null; try { FileStream fs = File.OpenRead(filename); zf = new ZipFile(fs); ZipEntry zipEntry = zf[0]; String entryFileName = zipEntry.Name; byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); StreamUtils.Copy(zipStream, toStream, buffer); } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } }
public Model Load(string fileName) { var document = new XmlDocument(); if (fileName.EndsWith(".tcn")) { var file = new ZipFile(new FileStream(fileName, FileMode.Open, FileAccess.Read)); var enumerator = file.GetEnumerator(); while (enumerator.MoveNext()) { if (((ZipEntry)enumerator.Current).Name.EndsWith(".xml")) { document.Load(file.GetInputStream((ZipEntry)enumerator.Current)); break; } } } else if (fileName.EndsWith(".xml")) document.Load(fileName); else throw new FileLoadException(); var tcnModel = new TCNFile(); tcnModel.Parse(document.DocumentElement); return tcnModel.Convert(); }
private List <string> reLoadModList() { modlistBox.Items.Clear(); var modlist = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory + "mods").ToList(); foreach (var item in modlist) { ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(item); var enrty = zip.FindEntry("config.json", true); if (enrty >= 0) { var config = MODConfigHelper.LoadConfig(zip.GetInputStream(enrty)); ModItemControl boxitem = new ModItemControl(); boxitem.ItemName = config.Name; //boxitem.IsRed = true; // ListBoxItem boxitem = new ListBoxItem(); // boxitem.Content = config.Name; boxitem.Tag = config; boxitem.DataContext = item; modlistBox.Items.Add(boxitem); } } return(modlist); }
public static bool try_extract_file_names_in_zip(string file_name, string extract_dir, Dictionary<string,string> extract_files) { try { using (var fs = new FileStream(file_name, FileMode.Open, FileAccess.Read)) { using (var zf = new ZipFile(fs)) { foreach (ZipEntry ze in zf) { if (ze.IsDirectory) continue; if (!extract_files.ContainsKey(ze.Name)) continue; string name = extract_dir + "\\" + extract_files[ze.Name]; using (Stream s = zf.GetInputStream(ze)) { byte[] buf = new byte[4096]; using (FileStream file = File.Create(name)) StreamUtils.Copy(s, file, buf); } } } } } catch(Exception e) { logger.Fatal("can't extract file " + file_name + ": " + e.Message); return false; } return true; }
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 EPubFile(Stream s) { try { zip = new ZipFile(s); string mpath = getRootFromContainer (GetContent("META-INF/container.xml")); OPFParser.ParseStream(GetContent(mpath), mpath, out Manifest, out Spine); if (Spine.TocId == null) { Toc = new TableOfContents(); } else { string tocPath = Manifest.GetById(Spine.TocId).Linkref; Toc = NCXParser.ParseStream(GetContent(tocPath), tocPath); } stream = s; } catch (Exception ex) { s.Dispose(); throw ex; } }
private AddIn LoadAddInFromZip(ZipFile file) { AddIn resultAddIn = null; ZipEntry addInEntry = null; foreach (ZipEntry entry in file) { if (entry.Name.EndsWith(".addin")) { if (addInEntry != null) { _events.OnAddInOperationError( new AddInOperationErrorEventArgs( SD.ResourceService.GetString("AddInManager2.InvalidPackage"))); return null; } addInEntry = entry; } } if (addInEntry == null) { _events.OnAddInOperationError( new AddInOperationErrorEventArgs( SD.ResourceService.GetString("AddInManager2.InvalidPackage"))); return null; } using (Stream s = file.GetInputStream(addInEntry)) { using (StreamReader r = new StreamReader(s)) { resultAddIn = _sdAddInManagement.Load(r); } } return resultAddIn; }
public AvcVersion GetInternalAvc(CkanModule module, string filePath, string internalFilePath = null) { using (var zipfile = new ZipFile(filePath)) { return GetInternalAvc(module, zipfile, internalFilePath); } }
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 { } }
/// <summary> /// Creates a new TestSuite instance. /// </summary> /// <param name="openFile"> A callback that can open a file for reading. </param> public TestSuite(Func<string, Stream> openFile) { if (openFile == null) throw new ArgumentNullException("openFile"); // Init collection. this.IncludedTests = new List<string>(); // Open the excludelist.xml file to generate a list of skipped file names. var reader = System.Xml.XmlReader.Create(openFile(@"config\excludeList.xml")); reader.ReadStartElement("excludeList"); do { if (reader.Depth == 1 && reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "test") this.skippedTestNames.Add(reader.GetAttribute("id")); } while (reader.Read()); // Read the include files. var includeBuilder = new System.Text.StringBuilder(); includeBuilder.AppendLine(ReadInclude(openFile, "cth.js")); includeBuilder.AppendLine(ReadInclude(openFile, "sta.js")); includeBuilder.AppendLine(ReadInclude(openFile, "ed.js")); this.includes = includeBuilder.ToString(); this.zipStream = openFile(@"suite\2012-05-18.zip"); this.zipFile = new ZipFile(this.zipStream); this.ApproximateTotalTestCount = (int)this.zipFile.Count; }
public void DataFileCorrectlyZipped() { string zipFile = null; try { m_backupSettings.DestinationFolder = m_backupSettings.ProjectPath; var filesToZip = new HashSet<String>(); filesToZip.Add(Path.Combine(m_backupSettings.ProjectPath, m_backupSettings.DbFilename)); zipFile = m_backupProjectService.BackupProjectWithFullPaths(new DummyProgressDlg(), filesToZip); //Now test if the file was actually created. Assert.True(File.Exists(zipFile), "The zip file was not created. It does not exist."); //ensure we have only one file in the zip file. using (var zip = new ZipFile(File.OpenRead(zipFile))) { Assert.AreEqual(1, zip.Count, "For this test there should only be one file in the zip file."); //We need to get the DataBasePath to match the format of the zip filenames. VerifyFileExistsInZipFile(zip, m_backupSettings.DbFilename); zip.Close(); } } finally { //Every time this test runs it produces a unique zipFile. Therefore delete it once the test completes. if (zipFile != null) File.Delete(zipFile); } }
private static void unzipDataFiles(string rootDir, string zipFile) { var zipFilePath = Path.Combine(rootDir, zipFile); var unzippedDirName = zipFile.Replace(".zip", ""); var fs = System.IO.File.OpenRead(zipFilePath); var zf = new ZipFile(fs); foreach (ZipEntry entry in zf) { if (entry.IsDirectory) { var directoryName = Path.Combine(rootDir, entry.Name); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); continue; } var entryFileName = entry.Name; Console.WriteLine("Unzipping {0}", entryFileName); var buffer = new byte[4096]; var zipStream = zf.GetInputStream(entry); var unzippedFilePath = Path.Combine(rootDir, entryFileName); using (var fsw = System.IO.File.Create(unzippedFilePath)) { StreamUtils.Copy(zipStream, fsw, buffer); } } zf.IsStreamOwner = true; zf.Close(); }
/// <summary> /// 解压数据。 /// </summary> /// <param name="path"></param> /// <param name="handler"></param> public static void UnZip(string path, UnZipStreamHanlder handler) { if (File.Exists(path) && handler != null) { lock (typeof(ZipTools)) { using (ZipFile zip = new ZipFile(File.Open(path, FileMode.Open, FileAccess.Read))) { foreach (ZipEntry entry in zip) { if (entry.IsFile && !string.IsNullOrEmpty(entry.Name)) { using (Stream stream = zip.GetInputStream(entry)) { if (stream != null) { handler(entry.Name, stream); } } } } } } } }
public void OpenZipFile() { ZipFile zipFile = new ZipFile(zipFileName); Dictionary<string, TestFile> xmlFiles = new Dictionary<string, TestFile>(); // Decompress XML files foreach(ZipEntry zipEntry in zipFile.Cast<ZipEntry>().Where(zip => zip.IsFile && zip.Name.EndsWith(".xml"))) { Stream stream = zipFile.GetInputStream(zipEntry); string content = new StreamReader(stream).ReadToEnd(); xmlFiles.Add(zipEntry.Name, new TestFile { Name = zipEntry.Name, Content = content }); } // Add descriptions foreach(TestFile metaData in xmlFiles.Values.Where(f => f.Name.StartsWith("ibm/ibm_oasis"))) { var doc = System.Xml.Linq.XDocument.Parse(metaData.Content); foreach(var testElem in doc.Descendants("TEST")) { string uri = "ibm/" + testElem.Attribute("URI").Value; string description = testElem.Value.Replace("\n ", "\n").TrimStart('\n'); if (xmlFiles.ContainsKey(uri)) xmlFiles[uri].Description = description; } } // Copy canonical forms foreach(TestFile canonical in xmlFiles.Values.Where(f => f.Name.Contains("/out/"))) { string uri = canonical.Name.Replace("/out/", "/"); if (xmlFiles.ContainsKey(uri)) xmlFiles[uri].Canonical = canonical.Content; } // Copy resuts to field this.xmlFiles.AddRange(xmlFiles.Values.Where(f => !f.Name.Contains("/out/"))); }
public void GenerateDefaultInstall() { string filename = TestData.DogeCoinFlagZip(); using (var zipfile = new ZipFile(filename)) { ModuleInstallDescriptor stanza = ModuleInstallDescriptor.DefaultInstallStanza("DogeCoinFlag", zipfile); TestDogeCoinStanza(stanza); // Same again, but screwing up the case (we see this *all the time*) ModuleInstallDescriptor stanza2 = ModuleInstallDescriptor.DefaultInstallStanza("DogecoinFlag", zipfile); TestDogeCoinStanza(stanza2); // Now what happens if we can't find what to install? Assert.Throws<FileNotFoundKraken>(delegate { ModuleInstallDescriptor.DefaultInstallStanza("Xyzzy", zipfile); }); // Make sure the FNFKraken looks like what we expect. try { ModuleInstallDescriptor.DefaultInstallStanza("Xyzzy", zipfile); } catch (FileNotFoundKraken kraken) { Assert.AreEqual("Xyzzy", kraken.file); } } }
public static void LoadPack(string packDir) { Dictionary<string, Dictionary<ushort, string>> allTextMap; using (var z = new ZipFile(Path.Combine(packDir, "text.zip"))) { using (var texter = new StreamReader(z.GetInputStream(z.GetEntry("text.csv")), Encoding.UTF8)) { allTextMap = CSV.ParseCSVText(texter); } } var byterList = new List<BinaryReader>(); var zipFiles = new List<ZipFile>(); foreach (var f in Directory.GetFiles(packDir, "*.zip")) { var name = Path.GetFileNameWithoutExtension(f); if (name != null && !name.Equals("text")) { var z = new ZipFile(f); zipFiles.Add(z); var byter = new BinaryReader(z.GetInputStream(z.GetEntry(name))); byterList.Add(byter); } } Processor(new Stream(byterList, allTextMap)); foreach (var z in zipFiles) { z.Close(); } }
/// <summary> /// Debugging method to get a list of all the file names within a zip file /// </summary> private static IList <string> GetZipFileNames(byte[] zipFileData) { List <string> names = new List <string>(); // Make a memory stream for the byte array MemoryStream ms = new MemoryStream(zipFileData); // Create the zip file ICSharpCode.SharpZipLib.Zip.ZipFile zf; try { zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(ms); } catch (Exception) { return(names); } // Go through the files within the zip foreach (ZipEntry ze in zf) { names.Add(ze.Name); } ms.Dispose(); return(names); }
/// <summary> /// ZIPファイルを指定されたフォルダに展開する /// </summary> /// <param name="contentsRootFolderPath">展開先のフォルダのパス</param> /// <param name="zipFilePath">展開対象のZIPファイルのパス</param> internal void ExtractZipFile(string contentsRootFolderPath, string zipFilePath) { var buffer = new byte[4096]; using (var zipFile = new Zip.ZipFile(zipFilePath)) { foreach (Zip.ZipEntry entry in zipFile) { var contentPath = Path.Combine(contentsRootFolderPath, entry.Name); var contentFolderPath = Path.GetDirectoryName(contentPath); if (!Directory.Exists(contentFolderPath)) { Directory.CreateDirectory(contentFolderPath); } if (!entry.IsFile) { continue; } var zipStream = zipFile.GetInputStream(entry); using (var outputStream = File.Create(contentPath)) { ZipCore.StreamUtils.Copy(zipStream, outputStream, buffer); } } } }
public static Node Generate(System.IO.FileInfo fileInfo) { ZipFile file = new ZipFile(fileInfo.FullName); Node node = new Node(); IDictionary<string, IList<Entry>> waiting = new Dictionary<string, IList<Entry>>(); foreach (ZipEntry zipEntry in file) { Entry entry = ParseEntry(zipEntry, node); if (entry != null) { string name = zipEntry.Name.TrimEnd('/'); string path = name.Substring(0, name.LastIndexOf('/')); if (!waiting.ContainsKey(path)) waiting[path] = new List<Entry>(); waiting[path].Add(entry); } if (zipEntry.IsDirectory && waiting.ContainsKey(zipEntry.Name.TrimEnd('/'))) { Node dir = GetDirectory(zipEntry.Name.TrimEnd('/'), node); if (dir != null) { foreach (var dirEntry in waiting[zipEntry.Name.TrimEnd('/')]) { dir.Nodes.Add(dirEntry); } waiting.Remove(zipEntry.Name.TrimEnd('/')); } } } FinalizeEntries(node, waiting, fileInfo); return node; }
private static Dictionary<string, object> GetIpaPList(string filePath) { var plist = new Dictionary<string, object>(); var zip = new ZipInputStream(File.OpenRead(filePath)); using (var filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { var zipfile = new ZipFile(filestream); ZipEntry item; while ((item = zip.GetNextEntry()) != null) { Match match = Regex.Match(item.Name.ToLower(), @"Payload/([A-Za-z0-9\-. ]+)\/info.plist$", RegexOptions.IgnoreCase); if (match.Success) { var bytes = new byte[50*1024]; using (Stream strm = zipfile.GetInputStream(item)) { int size = strm.Read(bytes, 0, bytes.Length); using (var s = new BinaryReader(strm)) { var bytes2 = new byte[size]; Array.Copy(bytes, bytes2, size); plist = (Dictionary<string, object>) PlistCS.readPlist(bytes2); } } break; } } } return plist; }
private void ExtractZipFile(string filepath) { FileStream fileReadStream = File.OpenRead(filepath); ZipFile zipFile = new ZipFile(fileReadStream); using (zipFile) { foreach (ZipEntry zipEntry in zipFile) { if (zipEntry.IsFile) { String entryFileName = zipEntry.Name; byte[] buffer = new byte[4096]; Stream zipStream = zipFile.GetInputStream(zipEntry); string fullZipToPath = Path.Combine(TempFolderForExtract, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } } }
/// <summary> /// Compares all idml's in outputPath to make sure the content.xml and styles.xml are the same /// </summary> public static void AreEqual(string expectFullName, string outputFullName, string msg) { using (var expFl = new ZipFile(expectFullName)) { var outFl = new ZipFile(outputFullName); foreach (ZipEntry zipEntry in expFl) { //TODO: designmap.xml should be tested but \\MetadataPacketPreference should be ignored as it contains the creation date. if (!CheckFile(zipEntry.Name,"Stories,Spreads,Resources,MasterSpreads")) continue; if (Path.GetExtension(zipEntry.Name) != ".xml") continue; string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd(); string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd(); XmlDocument outputDocument = new XmlDocument(); outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver(); outputDocument.LoadXml(outputEntry); XmlDocument expectDocument = new XmlDocument(); outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver(); expectDocument.LoadXml(expectEntry); XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform(); outputCanon.Resolver = new XmlUrlResolver(); outputCanon.LoadInput(outputDocument); XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform(); expectCanon.Resolver = new XmlUrlResolver(); expectCanon.LoadInput(expectDocument); Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream)); Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream)); string errMessage = string.Format("{0}: {1} doesn't match", msg, zipEntry.Name); Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage); FileAssert.AreEqual(expectStream, outputStream, errMessage); } } }
public void Basics() { const string tempName1 = "a(1).dat"; MemoryStream target = new MemoryStream(); string tempFilePath = GetTempFilePath(); Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); string addFile = Path.Combine(tempFilePath, tempName1); MakeTempFile(addFile, 1); try { FastZip fastZip = new FastZip(); fastZip.CreateZip(target, tempFilePath, false, @"a\(1\)\.dat", null); MemoryStream archive = new MemoryStream(target.ToArray()); using (ZipFile zf = new ZipFile(archive)) { Assert.AreEqual(1, zf.Count); ZipEntry entry = zf[0]; Assert.AreEqual(tempName1, entry.Name); Assert.AreEqual(1, entry.Size); Assert.IsTrue(zf.TestArchive(true)); zf.Close(); } } finally { File.Delete(tempName1); } }
// EXTRACT ZIP FILE private static void ExtractZipFile(string filePath) { var fileReadStram = File.OpenRead(filePath); var zipFile = new ZipFile(fileReadStram); // USING ZIP using (zipFile) { foreach (ZipEntry entry in zipFile) { if (entry.IsFile) { var entryFileName = entry.Name; var buffer = new byte[4096]; var zipStream = zipFile.GetInputStream(entry); var zipToPath = Path.Combine(TempFolderForExtract, entryFileName); var directoryName = Path.GetDirectoryName(zipToPath); if (directoryName != null && directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } using (var streamWriter = File.Create(zipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } } }
private static bool UnZip(string file) { var folder = Path.GetDirectoryName(file); if (folder == null) return false; using (var fs = File.OpenRead(file)) { using (var zf = new ZipFile(fs)) { foreach (ZipEntry entry in zf) { if (!entry.IsFile) continue; // Handle directories below var outputFile = Path.Combine(folder, entry.Name); var dir = Path.GetDirectoryName(outputFile); if (dir == null) continue; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); using (var stream = zf.GetInputStream(entry)) { using (var sw = File.Create(outputFile)) { stream.CopyTo(sw); } } } } } return true; }
/// <summary> /// Prepares to extract a ZIP archive contained in a stream. /// </summary> /// <param name="stream">The stream containing the archive data to be extracted. Will be disposed when the extractor is disposed.</param> /// <param name="target">The path to the directory to extract into.</param> /// <exception cref="IOException">The archive is damaged.</exception> internal ZipExtractor([NotNull] Stream stream, [NotNull] string target) : base(target) { #region Sanity checks if (stream == null) throw new ArgumentNullException("stream"); #endregion UnitsTotal = stream.Length; try { // Read the central directory using (var zipFile = new ZipFile(stream) {IsStreamOwner = false}) { _centralDirectory = new ZipEntry[zipFile.Count]; for (int i = 0; i < _centralDirectory.Length; i++) _centralDirectory[i] = zipFile[i]; } stream.Seek(0, SeekOrigin.Begin); _zipStream = new ZipInputStream(stream); } #region Error handling catch (ZipException ex) { // Wrap exception since only certain exception types are allowed throw new IOException(Resources.ArchiveInvalid, ex); } #endregion }
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); }
static FileMapping[] GetFileMaps(ICSharpCode.SharpZipLib.Zip.ZipFile zipArchive) { try { var entry = zipArchive.Cast <ZipEntry>().FirstOrDefault(f => f.Name.ToLower() == "config.json"); if (entry != null) { var buffer = new byte[entry.Size]; using (var stream = zipArchive.GetInputStream(entry)) { StreamUtils.ReadFully(stream, buffer); } var json = Encoding.UTF8.GetString(buffer); var jObject = JsonHelper.DeserializeJObject(json); if (jObject.TryGetValue("mappings", out var obj)) { return(obj.ToObject <FileMapping[]>()); } } } catch (Exception) { } return(new FileMapping[0]); }
public static void LoadZip(this VirtualResources virtualResources, string zipPath, string rootPath, ZipOption zipOption) { if (!File.Exists(zipPath)) { // throw new FileNotFoundException(); return; } var zipArchive = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath); zipPath = Helper.NormalizePath(zipPath); _zipArchives[zipPath] = zipArchive; var dir = GetZipVirtualPath(zipPath); var fileMaps = GetFileMaps(zipArchive); foreach (ZipEntry item in zipArchive) { var path = Path.Combine(dir, item.Name); path = Helper.NormalizePath(path); if (item.IsDirectory) { var virtualDirectory = new VirtualDirectory(path, "zip"); virtualResources._entries[path] = virtualDirectory; } else { var fileMap = fileMaps.FirstOrDefault(f => f.To == item.Name); if (fileMap != null) { fileMap.From = fileMap.From.Trim(); if (fileMap.From.StartsWith("/")) { fileMap.From = fileMap.From.Substring(1); } var fromPath = Path.Combine(rootPath, fileMap.From); var fileMapFrom = Helper.NormalizePath(fromPath); var virtualFile = new ZipFile(item, zipArchive, fileMapFrom, zipPath, zipOption); virtualResources._fileMaps[fileMapFrom] = virtualFile; } virtualResources._entries[path] = new ZipFile(item, zipArchive, path, zipPath, zipOption); while (true) { if (path == dir) { break; } path = Path.GetDirectoryName(path); if (virtualResources._entries.Where(w => w.Value is VirtualDirectory).All(a => a.Key != path)) { virtualResources._entries[path] = new VirtualDirectory(path, "zip"); } } } } }
ZipFile(string filename, IReadWritePackage parent) { pkgStream = new MemoryStream(); Name = filename; Parent = parent; pkg = SZipFile.Create(pkgStream); }
public void UndoRedoButton(bool undoFlag) { string str; try { if (undoFlag == true) { str = undoList[undoListNum - 1]; undoListNum--; } else { str = undoList[undoListNum + 1]; undoListNum++; } mapData.Clear(); for (int i = 0; i < objIB.Count; i++) { Destroy(objIB[i]); } objIB.Clear(); // 読み込んだ目次テキストファイルからstring配列を作成する mapData.AddRange(str.Split('\n')); mapData.RemoveAt(mapData.Count - 1); //最後の行は空白なので消す //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; 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(); } catch { if (undoFlag == true) { GameObject.Find("Error").GetComponent <Text>().text = "これ以上戻れません。"; } if (undoFlag == false) { GameObject.Find("Error").GetComponent <Text>().text = "これ以上進めません。"; } StartCoroutine(ErrorWait()); } selectNum = -1; }
private void OpenZlib() { if (this.Options.ReadOnly) { this.zipFile = new ZLib.ZipFile(this.ParentLayer.GetContent().GetInputStream(FileShare.ReadWrite)); } else { this.zipFile = new ZLib.ZipFile(this.ParentLayer.GetContent().OpenStream(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)); } }
public void PushPasswordButton() { string pass; string text = ""; pass = pass2Obj.GetComponent <InputField>().text; try { //閲覧するエントリ string extractFile = "[system]password[system].txt"; //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; //展開するエントリを探す ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile); try { if (ze != null) { //閲覧するZIPエントリのStreamを取得 System.IO.Stream reader = zf.GetInputStream(ze); //文字コードを指定してStreamReaderを作成 System.IO.StreamReader sr = new System.IO.StreamReader( reader, System.Text.Encoding.GetEncoding("UTF-8")); // テキストを取り出す text = sr.ReadToEnd(); //閉じる sr.Close(); reader.Close(); } } catch { } //閉じる zf.Close(); } catch { GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "シナリオファイルに異常があります。"; return; } if (text == "" || text == pass) { GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "MapScene"); } else { GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "パスワードが違います。"; return; } }
public ZipFile(Stream stream, string name, IReadOnlyPackage parent = null) { // SharpZipLib breaks when asked to update archives loaded from outside streams or files // We can work around this by creating a clean in-memory-only file, cutting all outside references pkgStream = new MemoryStream(); stream.CopyTo(pkgStream); pkgStream.Position = 0; Name = name; Parent = parent as IReadWritePackage; pkg = new SZipFile(pkgStream); }
private static Dictionary <string, string> ReadArchive(Stream fs, Dictionary <string, string> dataToFill) { ZipFile zipArchive = new ZipFile(fs); foreach (ZipEntry elementInsideZip in zipArchive) { String ZipArchiveName = elementInsideZip.Name; if (ZipArchiveName.Contains(".txt") || !ZipArchiveName.Contains("/")) { Stream zipStream = zipArchive.GetInputStream(elementInsideZip); var bytes = new byte[zipStream.Length]; zipStream.Read(bytes, 0, (int)zipStream.Length); dataToFill.Add(elementInsideZip.Name, Encoding.UTF8.GetString(bytes)); } else if (ZipArchiveName.Contains(".zip")) { Stream zipStream = zipArchive.GetInputStream(elementInsideZip); string zipFileExtractPath = Path.GetTempFileName(); FileStream extractedZipFile = File.OpenWrite(zipFileExtractPath); zipStream.CopyTo(extractedZipFile); extractedZipFile.Flush(); extractedZipFile.Close(); try { OpenArchive(zipFileExtractPath, dataToFill); } finally { File.Delete(zipFileExtractPath); } } else if (ZipArchiveName.Contains("/")) { Stream zipStream = zipArchive.GetInputStream(elementInsideZip); string zipDirExtractPath = Path.GetTempPath(); string zipFileExtractPath = Path.GetTempFileName(); FileStream extractedZipFile = File.OpenWrite(Path.Combine(zipDirExtractPath, zipFileExtractPath)); zipStream.CopyTo(extractedZipFile); extractedZipFile.Flush(); extractedZipFile.Close(); try { OpenArchive(zipFileExtractPath, dataToFill); } finally { File.Delete(zipFileExtractPath); } } } return(dataToFill); }
// Create a new zip with the specified contents public ZipFile(string filename, int priority, Dictionary <string, byte[]> contents) { this.priority = priority; this.filename = filename; if (File.Exists(filename)) { File.Delete(filename); } pkg = SZipFile.Create(filename); Write(contents); }
public ZipFile(IReadOnlyFileSystem context, string filename, bool createOrClearContents = false) { Name = filename; if (createOrClearContents) { pkg = SZipFile.Create(filename); } else { pkg = new SZipFile(filename); } }
public ZipFile(FileSystem context, string filename, Stream stream, bool createOrClearContents = false) { Name = filename; if (createOrClearContents) { pkg = SZipFile.Create(stream); } else { pkg = new SZipFile(stream); } }
public static void ExtractZipFile(string archiveFilenameIn, string password, string outFolder, string justThisFile = null) { ICSharpCode.SharpZipLib.Zip.ZipFile zf = null; try { FileStream fs = File.OpenRead(archiveFilenameIn); zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); if (!String.IsNullOrEmpty(password)) { zf.Password = password; } foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; } if (!String.IsNullOrEmpty(justThisFile) && zipEntry.Name != justThisFile) { continue; } String entryFileName = zipEntry.Name; byte[] buffer = new byte[4096]; // 4K is optimum Stream zipStream = zf.GetInputStream(zipEntry); // Manipulate the output filename here as desired. String fullZipToPath = Path.Combine(outFolder, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); // Ensure we release resources } } }
public ZipFile(string filename, int priority) { this.filename = filename; this.priority = priority; try { // pull the file into memory, dont keep it open. pkg = new SZipFile(new MemoryStream(File.ReadAllBytes(filename))); } catch (ZipException e) { Log.Write("debug", "Couldn't load zip file: {0}", e.Message); } }
public static void DecompressFile(string projectFilePath, string targetDirectory) { FileStream fs = File.OpenRead(projectFilePath); ZipFile file = new ZipFile(fs); foreach (ZipEntry zipEntry in file) { if (!zipEntry.IsFile) { // Ignore directories but create them in case they're empty Directory.CreateDirectory(Path.Combine(targetDirectory, zipEntry.Name)); continue; } //exclude nuget metadata files string[] excludedFiles = { ".nuspec", ".xml", ".rels", ".psmdcp" }; if (excludedFiles.Any(e => Path.GetExtension(zipEntry.Name) == e)) { continue; } string entryFileName = Uri.UnescapeDataString(zipEntry.Name); // 4K is optimum byte[] buffer = new byte[4096]; Stream zipStream = file.GetInputStream(zipEntry); // Manipulate the output filename here as desired. string fullZipToPath = Path.Combine(targetDirectory, entryFileName); string directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size // of the file, but does not waste memory. // The "using" will close the stream even if an exception occurs. using (FileStream streamWriter = File.Create(fullZipToPath)) StreamUtils.Copy(zipStream, streamWriter, buffer); } if (file != null) { file.IsStreamOwner = true; file.Close(); } }
/// <summary> /// Uses the SharpZipLib to unzip a file /// </summary> /// <param name="archiveFilenameIn">Location of the file to be unzipped</param> /// <param name="outFolder">Where the unzipped files should be placed</param> /// <param name="password">Optional parameter to allow for the handling of AES encrypted files.</param> private static void ExtractZipFile(string archiveFilenameIn, string outFolder, string password = null) { try { using (var fs = File.OpenRead(archiveFilenameIn)) using (var zf = new SharpZip.ZipFile(fs)) { zf.IsStreamOwner = true; if (!string.IsNullOrEmpty(password)) { zf.Password = password; //AES encrypted entries are handled automatically } foreach (SharpZip.ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) { continue; //Ignore Directories } var entryFileName = zipEntry.Name; if (!entryFileName.EndsWith(".pdf", StringComparison.InvariantCultureIgnoreCase)) { continue; } var buffer = new byte[4096]; var zipStream = zf.GetInputStream(zipEntry); var fullZipToPath = Path.Combine(outFolder, entryFileName); using (var streamWriter = File.Create(fullZipToPath)) StreamUtils.Copy(zipStream, streamWriter, buffer); } } } catch (Exception) { var errorMessage = archiveFilenameIn + " was unable to be opened. File is likely corrupted."; try { SendCorruptFileEmail(errorMessage); } catch (Exception) { LogErrorToFile(archiveFilenameIn, errorMessage); } } }
private static IFile GetZipFile(IFile zipFile) { if (zipFile.Address.QueryValues["shadow"] as string == "true") { return(zipFile); } if (ConfigurationSection.Instance.AutoShadowThreshold == -1 || zipFile.Length <= ConfigurationSection.Instance.AutoShadowThreshold) { zipFile = zipFile.ResolveFile(StringUriUtils.AppendQueryPart(zipFile.Address.NameAndQuery, "shadow", "true")); } return(zipFile); }
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))); }
//目次ファイルを読み込み、進行度に合わせてファイルを拾ってくる。 private void LoadMapData(string path) { try { //閲覧するエントリ string extractFile = path; //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; //展開するエントリを探す ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile); if (ze != null) { //閲覧するZIPエントリのStreamを取得 System.IO.Stream reader = zf.GetInputStream(ze); //文字コードを指定してStreamReaderを作成 System.IO.StreamReader sr = new System.IO.StreamReader( reader, System.Text.Encoding.GetEncoding("UTF-8")); // テキストを取り出す string text = sr.ReadToEnd(); // 読み込んだ目次テキストファイルからstring配列を作成する mapData = text.Split('\n'); //閉じる sr.Close(); reader.Close(); mapLoad = true; } else { obj.GetComponent <Text>().text = ("[エラー]\nシナリオファイルの異常"); ErrorBack(); mapData = new string[0]; } //閉じる zf.Close(); } catch { obj.GetComponent <Text>().text = ("[エラー]\nシナリオファイルの異常"); ErrorBack(); mapData = new string[0]; } }
static void ExtractZipDirectory(string archname, string directoryname) { // 4K is optimum byte[] buffer = new byte[4096]; try { using (System.IO.Stream source = System.IO.File.Open(archname, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { //! archive file load to stream ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(source); try { foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zipFile) { if (!entry.IsFile) { continue; } if (entry.IsCrypted) { throw new Exception("Compress file encrypted."); } string filetobecreate = System.IO.Path.Combine(directoryname, entry.Name); using (System.IO.Stream data = zipFile.GetInputStream(entry)) { using (System.IO.Stream write = System.IO.File.Open(filetobecreate, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None)) { ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(data, write, buffer); write.Close(); } data.Close(); } } } finally { zipFile.IsStreamOwner = true; zipFile.Close(); } } } catch (System.IO.IOException ex) { Console.WriteLine(ex.Message); } }
public void ScenarioFileCheck(int num, ICSharpCode.SharpZipLib.Zip.ZipFile zf) { string[] strs; strs = mapData[num].Replace("\r", "").Replace("\n", "").Split(',');//strs[11]がシナリオパス try { //展開するエントリを探す ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(strs[11]); //参照先のファイルがあるか調べる。なかったら(未)をつける。 if (ze == null) { objIB[num].GetComponentInChildren <Text>().text = "(未)" + objIB[num].GetComponentInChildren <Text>().text; } } catch { } }