GetInputStream() public method

Gets an input stream for reading the given zip entry data in an uncompressed form. Normally the ZipEntry should be an entry returned by GetEntry().
/// The ZipFile has already been closed /// /// The compression method for the entry is unknown /// /// The entry is not found in the ZipFile ///
public GetInputStream ( ZipEntry entry ) : Stream
entry ZipEntry The to obtain a data for
return Stream
Exemplo n.º 1
0
        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();
        }
Exemplo n.º 2
0
        public List<Type> Search(string s, List<string> imports)
        {
            if (JbtLocator != null)
            {
                return JbtLocator.Search(s, imports);
            }

            var zf = new ZipFile(JarFile);

            string[] classParts = s.Split('.');
            string classFolder = string.Join("\\", classParts.Take(classParts.Length - 1));
            string className = classParts.Last() + ".class";

            bool isAbsolute = !string.IsNullOrEmpty(classFolder);

            var types = new List<Type>();
            foreach (ZipEntry ze in zf)
            {
                if (!ze.IsFile) continue;

                string fileName = Path.GetFileName(ze.Name);
                string directoryName = Path.GetDirectoryName(ze.Name);

                if (isAbsolute)
                {
                    // absolute
                    if (directoryName == classFolder && fileName == className)
                    {
                        types.Add(ClassLoader.Load(zf.GetInputStream(ze)));
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(directoryName) && fileName == className)
                    {
                        types.Add(ClassLoader.Load(zf.GetInputStream(ze)));
                    }
                    else
                    {
                        foreach (string import in imports)
                        {
                            string[] importParts = import.Split('.');
                            string importFolder = string.Join("\\", importParts.Take(importParts.Length - 1));
                            string importName = importParts.Last();

                            if (!(importName == "*" || importName + ".class" == className)) continue;

                            if (importFolder == directoryName && fileName == className)
                            {
                                types.Add(ClassLoader.Load(zf.GetInputStream(ze)));
                            }
                        }
                    }
                }
            }

            return types;
        }
Exemplo n.º 3
0
        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);
        }
Exemplo n.º 4
0
        public DocxImporter(string file)
        {
            zip = new ZipFile (file);

            var docEntry = zip.GetEntry (DocumentXmlEntry);
            if (docEntry == null)
                throw new DocxFormatException (string.Format ("Zip entry '{0}' not found", DocumentXmlEntry));

            docXml = XDocument.Load (zip.GetInputStream (docEntry.ZipFileIndex));

            var relsEntry = zip.GetEntry (DocumentRelsEntry);
            if (relsEntry != null)
                relsXml = XDocument.Load (zip.GetInputStream (relsEntry.ZipFileIndex));
        }
Exemplo n.º 5
0
        public static bool InstalledNewVersion()
        {
            var packagedZip = HostingEnvironment.MapPath("~/Packaged.zip");

            if (!File.Exists(packagedZip))
                return false;

            _updating = true;

            var webFolder = HostingEnvironment.MapPath("~");
            var buffer = new byte[4096];

            using (var zipFile = new ZipFile(packagedZip))
                foreach (ZipEntry zipEntry in zipFile)
                {
                    var outFile = Path.Combine(webFolder, zipEntry.Name);
                    Directory.CreateDirectory(Path.GetDirectoryName(outFile));

                    using (var streamWriter = File.Create(outFile))
                        StreamUtils.Copy(zipFile.GetInputStream(zipEntry), streamWriter, buffer);
                }

            var deployedZip = HostingEnvironment.MapPath("~/Deployed.zip");

            if (File.Exists(deployedZip))
                File.Delete(deployedZip);

            File.Move(packagedZip, deployedZip);

            // in case the app hasn't recycled
            HttpRuntime.UnloadAppDomain();

            return true;
        }
Exemplo n.º 6
0
        static void ConvertZip(string filename)
        {
            string basep = Path.GetDirectoryName(filename);
            string plain = Path.GetFileNameWithoutExtension(filename);

            using (HfsFile hfs = HfsFile.Create(basep + @"\" + plain + "_.hfs"))
            using (ZipFile zip = new ZipFile(filename))
            {
                hfs.BeginUpdate();

                if (zip.ZipFileComment == "extra_obscure")
                {
                    // could be better implemented
                    hfs.ObfuscationKey = -1;
                }

                foreach (ZipEntry zipEntry in zip)
                {
                    Console.WriteLine("Processing " + zipEntry.Name);

                    Stream read = zip.GetInputStream(zipEntry);

                    hfs.Add(new StreamLocalSourceHfs(read), zipEntry.Name);
                }

                Console.WriteLine("Compressing..");
                hfs.CommitUpdate();
            }

            Console.WriteLine("Wrote to " + basep + @"\" + plain + "_.hfs");
        }
        void TestLargeZip(string tempFile, int targetFiles)
        {
            const int BlockSize = 4096;

            byte[] data = new byte[BlockSize];
            byte nextValue = 0;
            for (int i = 0; i < BlockSize; ++i)
            {
                nextValue = ScatterValue(nextValue);
                data[i] = nextValue;
            }

            using (ZipFile zFile = new ZipFile(tempFile))
            {
                Assert.AreEqual(targetFiles, zFile.Count);
                byte[] readData = new byte[BlockSize];
                int readIndex;
                foreach (ZipEntry ze in zFile)
                {
                    Stream s = zFile.GetInputStream(ze);
                    readIndex = 0;
                    while (readIndex < readData.Length)
                    {
                        readIndex += s.Read(readData, readIndex, data.Length - readIndex);
                    }

                    for (int ii = 0; ii < BlockSize; ++ii)
                    {
                        Assert.AreEqual(data[ii], readData[ii]);
                    }
                }
                zFile.Close();
            }
        }
Exemplo n.º 8
0
        public static bool FromFile(string fileName, out ThemePack result)
        {
            var fiSource = new FileInfo(fileName);

            using (var fs = new FileStream(fiSource.FullName, FileMode.Open, FileAccess.Read))
            using (var zf = new ZipFile(fs))
            {
                var ze = zf.GetEntry("info.json");
                if (ze == null)
                {
                    result = null;
                    return false;
                }

                using (var s = zf.GetInputStream(ze))
                using (var reader = new StreamReader(s))
                {
                    var themePack = JsonConvert.DeserializeObject<ThemePack>(reader.ReadToEnd());
                    themePack.FileName = fiSource.Name;

                    result = themePack;
                    return true;
                }
            }
        }
Exemplo n.º 9
0
        // 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);
                        }
                    }
                }
            }
        }
Exemplo n.º 10
0
        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);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        public static void UnZipFB2File(string archiveFileName, string fb2FileId, string outputFolder)
        {
            using (ZipFile zf = new ZipFile(File.OpenRead(archiveFileName)))
            {
                foreach (ZipEntry theEntry in zf)
                {

                    string directoryName = outputFolder;//Path.GetDirectoryName(theEntry.Name);
                    string fileName = directoryName + "\\" + Path.GetFileName(theEntry.Name);

                    // create directory
                    if (directoryName.Length > 0 && !Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (fileName != String.Empty && Path.GetFileName(fileName).ToLower().Equals(fb2FileId))
                    {
                        byte[] buffer = new byte[4096];
                        Stream zipStream = zf.GetInputStream(theEntry);
                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                        break;
                    }
                }
            }
        }
Exemplo n.º 12
0
 /// <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);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 13
0
        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]);
        }
        private Action<Stream> GetFileFromZip(string zipPath, string docPath)
        {
            var fileStream = new FileStream(zipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var zipFile = new ZipFile(fileStream);
            var zipEntry = zipFile.GetEntry(docPath);

            if (zipEntry == null || zipEntry.IsFile == false)
                return null;

            var data = zipFile.GetInputStream(zipEntry);
            if (data == null) return null;

            return stream =>
                   {
                       try
                       {
                           if (_disableRequestCompression == false)
                               stream = new GZipStream(stream, CompressionMode.Compress, leaveOpen: true);

                           data.CopyTo(stream);
                           stream.Flush();
                       }
                       finally
                       {
                           if (_disableRequestCompression == false)
                               stream.Dispose();
                       }
                   };
        }
Exemplo n.º 15
0
        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
                }
            }
        }
Exemplo n.º 16
0
 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);
                 }
             }
         }
     }
 }
Exemplo n.º 17
0
        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();
            }
        }
Exemplo n.º 18
0
        /// <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);
                    }
                }
            }
        }
Exemplo n.º 19
0
        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();
        }
Exemplo n.º 20
0
 /// <summary>
 /// extract file from zipped resource, and place to temp folder
 /// </summary>
 /// <param name="resource">resource name</param>
 /// <param name="fileName">output name</param>
 /// <param name="OverWriteIfExists">if true,will overwrite the file even if the file exists</param>
 private void ExtractResourceZip(byte[] resource, string fileName, bool OverWriteIfExists = false, int BufferSize = BUFFERSIZE)
 {
     string target = WorkingPath + fileName;
     
     if (OverWriteIfExists || !File.Exists(target))
     {
         ZipFile zip = null;
         FileStream fs = null;
         Stream inStream = null;
         try
         {
             zip = new ZipFile(new MemoryStream(resource));
             inStream = zip.GetInputStream(zip.GetEntry(fileName));
             fs = new FileStream(target, FileMode.Create);
             byte[] buff = new byte[BufferSize];
             int read_count;
             while ((read_count = inStream.Read(buff, 0, BufferSize)) > 0)
             {
                 fs.Write(buff, 0, read_count);
             }
         }
         catch { }
         finally
         {
             if (zip != null) zip.Close();
             if (fs != null) fs.Close();
             if (inStream != null) inStream.Close();
         }
     }
 }
Exemplo n.º 21
0
        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);
        }
Exemplo n.º 22
0
        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 {
                return false;
            }

            return true;
        }
Exemplo n.º 23
0
		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/")));
		}
Exemplo n.º 24
0
        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;
        }
Exemplo n.º 25
0
 /// <summary>
 /// Compares all odt's in outputPath to make sure the content.xml and styles.xml are the same
 /// </summary>
 /// <param name="expectPath">expected output path</param>
 /// <param name="outputPath">output path</param>
 /// <param name="msg">message to display if mismatch</param>
 public static void AreEqual(string expectPath, string outputPath, string msg)
 {
     var outDi = new DirectoryInfo(outputPath);
     var expDi = new DirectoryInfo(expectPath);
     FileInfo[] outFi = outDi.GetFiles("*.od*");
     FileInfo[] expFi = expDi.GetFiles("*.od*");
     Assert.AreEqual(outFi.Length, expFi.Length, string.Format("{0} {1} odt found {2} expected", msg, outFi.Length, expFi.Length));
     foreach (FileInfo fi in outFi)
     {
         var outFl = new ZipFile(fi.FullName);
         var expFl = new ZipFile(Common.PathCombine(expectPath, fi.Name));
         foreach (string name in "content.xml,styles.xml".Split(','))
         {
             string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(name).ZipFileIndex)).ReadToEnd();
             string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(name).ZipFileIndex)).ReadToEnd();
             XmlDocument outputDocument = new XmlDocument();
             outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver();
             outputDocument.LoadXml(outputEntry);
             XmlDocument expectDocument = new XmlDocument();
             expectDocument.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} {2} doesn't match", msg, fi.Name, name);
             Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage);
             FileAssert.AreEqual(expectStream, outputStream, errMessage);
         }
     }
 }
Exemplo n.º 26
0
        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
                }
            }
        }
Exemplo n.º 27
0
        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);
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
        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;
        }
Exemplo n.º 29
0
 /// <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);
         }
     }
 }
Exemplo n.º 30
0
        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;
        }
Exemplo n.º 31
0
		public static void DecompressZipFileFromStream(Stream inputStream, string outFolder)
		{
			using (var zf = new ZipFile(inputStream))
			{
				zf.IsStreamOwner = false;
				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.

					var 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);
					}
				}
			}
		}
Exemplo n.º 32
0
        public bool install(string target)
        {
            if (!File.Exists(target))
            {
                return false;
            }
            ZipFile zip = new ZipFile(target);
            bool neednewgamedirectory = true;
            try
            {
                foreach (ZipEntry item in zip)
                {
                    if (item.Name.StartsWith(MeCore.Config.Server.ClientPath ?? ".minecraft"))
                    {
                        neednewgamedirectory = false;
                        continue;
                    }
                    if (!item.IsFile)
                    {
                        continue;
                    }
                    string entryFileName = item.Name;
                    byte[] buffer = new byte[4096];
                    Stream zipStream = zip.GetInputStream(item);
                    string fullZipToPath = "";
                    if (neednewgamedirectory)
                    {
                        fullZipToPath = Path.Combine(MeCore.BaseDirectory, MeCore.Config.Server.ClientPath ?? ".minecraft", entryFileName);
                    }
                    else
                    {
                        fullZipToPath = Path.Combine(MeCore.BaseDirectory, entryFileName);
                    }

                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                MeCore.Invoke(new Action(() => MeCore.MainWindow.addNotice(new Notice.CrashErrorBar(string.Format(LangManager.GetLangFromResource("ErrorNameFormat"), DateTime.Now.ToLongTimeString()), ex.ToWellKnownExceptionString()) { ImgSrc = new BitmapImage(new Uri("pack://application:,,,/Resources/error-banner.jpg")) })));

            }
            finally
            {
                if (zip != null)
                {
                    zip.IsStreamOwner = true;
                    zip.Close();
                }
            }
            return true;
        }
Exemplo n.º 33
0
 public static Stream GetPartStream(ZipFile zipFile, ZipEntry zipEntry)
 {
     MemoryStream partStream = new MemoryStream();
     Stream inputStream = zipFile.GetInputStream(zipEntry);
     Stream seekableStream = GetSeekableStream(inputStream);
     CopyStream(seekableStream, partStream);
     return partStream;
 }
Exemplo n.º 34
0
		public SeekableZipStream(ZipFile file, ZipEntry entry)
		{
			zipFile = file;
			zipEntry = entry;
			zipStream = zipFile.GetInputStream(zipEntry);
			temp = new byte[65536];
			position = 0;
		}
Exemplo n.º 35
0
      public static DirectoryInfo Unzip(FileInfo downloadedFile, bool deleteZip)
      {
         // Generate a unique output directory.
         string outDir = TempPath.GenerateTempDirectory("Senesco Upgrade Files");
         Directory.CreateDirectory(outDir);

         // Unzip to the target directory.
         using (FileStream fs = downloadedFile.OpenRead())
         {
            byte[] buffer = new byte[4096]; // 4K unzipping buffer
            ZipFile zip = new ZipFile(fs);
            foreach (ZipEntry entry in zip)
            {
               // Ignore directories since we create them as needed from the file paths.
               if (entry.IsFile == false)
                  continue;

               // Relative path of this file.
               String fileName = entry.Name;
               Stream zipStream = zip.GetInputStream(entry);

               // Compile the target unzip full path.
               String targetFilePath = Path.Combine(outDir, fileName);

               // Create target directory if needed.
               string directoryName = Path.GetDirectoryName(targetFilePath);
               if (String.IsNullOrEmpty(directoryName) == false)
               {
                  Directory.CreateDirectory(directoryName);
               }

               // Unzip using the buffer.
               using (FileStream streamWriter = File.Create(targetFilePath))
               {
                  StreamUtils.Copy(zipStream, streamWriter, buffer);
               }
            }
         }

         // If there were no exceptions, delete the zip file.
         if (deleteZip)
         {
            downloadedFile.Delete();
         }

         // If the unzip dir is a single wrapping dir, return the inner dir.
         if (Directory.GetFiles(outDir).Length == 0)
         {
            string[] directories = Directory.GetDirectories(outDir);
            if (directories.Length == 1)
            {
               return new DirectoryInfo(directories[0]);
            }
         }

         return new DirectoryInfo(outDir);
      }
Exemplo n.º 36
0
        public void MakeBloomPack_AddslockFormattingMetaTagToReader()
        {
            var srcBookPath = MakeBook();

            // the html file needs to have the same name as its directory
            var testFileName = Path.GetFileName(srcBookPath) + ".htm";
            var readerName = Path.Combine(srcBookPath, testFileName);

            var bloomPackName = Path.Combine(_folder.Path, "testReaderPack.BloomPack");

            var sb = new StringBuilder();
            sb.AppendLine("<!DOCTYPE html>");
            sb.AppendLine("<html>");
            sb.AppendLine("<head>");
            sb.AppendLine("    <meta charset=\"UTF-8\"></meta>");
            sb.AppendLine("    <meta name=\"Generator\" content=\"Bloom Version 3.3.0 (apparent build date: 28-Jul-2015)\"></meta>");
            sb.AppendLine("    <meta name=\"BloomFormatVersion\" content=\"2.0\"></meta>");
            sb.AppendLine("    <meta name=\"pageTemplateSource\" content=\"Leveled Reader\"></meta>");
            sb.AppendLine("    <title>Leveled Reader</title>");
            sb.AppendLine("    <link rel=\"stylesheet\" href=\"basePage.css\" type=\"text/css\"></link>");
            sb.AppendLine("</head>");
            sb.AppendLine("<body>");
            sb.AppendLine("</body>");
            sb.AppendLine("</html>");

            File.WriteAllText(readerName, sb.ToString());

            // make the BloomPack
            MakeTestBloomPack(bloomPackName, true);

            // get the reader file from the BloomPack
            var actualFiles = GetActualFilenamesFromZipfile(bloomPackName);
            var zipEntryName = actualFiles.FirstOrDefault(file => file.EndsWith(testFileName));
            Assert.That(zipEntryName, Is.Not.Null.And.Not.Empty);

            string outputText;
            using (var zip = new ZipFile(bloomPackName))
            {
                var ze = zip.GetEntry(zipEntryName);
                var buffer = new byte[4096];

                using (var instream = zip.GetInputStream(ze))
                using (var writer = new MemoryStream())
                {
                    ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(instream, writer, buffer);
                    writer.Position = 0;
                    using (var reader = new StreamReader(writer))
                    {
                        outputText = reader.ReadToEnd();
                    }
                }
            }

            // check for the lockFormatting meta tag
            Assert.That(outputText, Is.Not.Null.And.Not.Empty);
            Assert.IsTrue(outputText.Contains("<meta name=\"lockFormatting\" content=\"true\">"));
        }
Exemplo n.º 37
0
 public Stream GetContent(string filename)
 {
     using (var z = pkg.GetInputStream(pkg.GetEntry(filename)))
     {
         var ms = new MemoryStream();
         z.CopyTo(ms);
         ms.Seek(0, SeekOrigin.Begin);
         return(ms);
     }
 }
Exemplo n.º 38
0
    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;
        }
    }
Exemplo n.º 39
0
        public static ApkInfo ReadApkFromPath(string path)
        {
            NativeMethods.Log("ReadApkFromPath: " + path);
            byte[] manifestData  = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }
                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                }
                            }
                        }
                    }
                }
            }

            ApkReader apkReader = new ApkReader();
            ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);

            return(info);
        }
Exemplo n.º 40
0
    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
            }
        }
    }
Exemplo n.º 41
0
        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();
            }
        }
Exemplo n.º 42
0
        /// <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);
                }
            }
        }
Exemplo n.º 43
0
        public Stream GetContent(string filename)
        {
            using (var z = pkg.GetInputStream(pkg.GetEntry(filename)))
            {
                var    ms      = new MemoryStream();
                int    bufSize = 2048;
                byte[] buf     = new byte[bufSize];
                while ((bufSize = z.Read(buf, 0, buf.Length)) > 0)
                {
                    ms.Write(buf, 0, bufSize);
                }

                ms.Seek(0, SeekOrigin.Begin);
                return(ms);
            }
        }
Exemplo n.º 44
0
    //目次ファイルを読み込み、進行度に合わせてファイルを拾ってくる。
    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];
        }
    }
Exemplo n.º 45
0
        public Stream GetStream(string filename)
        {
            var entry = pkg.GetEntry(filename);

            if (entry == null)
            {
                return(null);
            }

            using (var z = pkg.GetInputStream(entry))
            {
                var ms = new MemoryStream();
                z.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                return(ms);
            }
        }
Exemplo n.º 46
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);
     }
 }
Exemplo n.º 47
0
        public static void UncompressZip(string archiveFile, string directory)
        {
            Log.Information("Uncompressing {File} to {Directory} ...", Path.GetFileName(archiveFile), directory);

            using var fileStream = File.OpenRead(archiveFile);
            using var zipFile    = new ICSharpCode.SharpZipLib.Zip.ZipFile(fileStream);

            var entries = zipFile.Cast <ZipEntry>().Where(x => !x.IsDirectory);

            foreach (var entry in entries)
            {
                var file = PathConstruction.Combine(directory, entry.Name);
                FileSystemTasks.EnsureExistingParentDirectory(file);

                using var entryStream  = zipFile.GetInputStream(entry);
                using var outputStream = File.Open(file, FileMode.Create);
                entryStream.CopyTo(outputStream);
            }
        }
Exemplo n.º 48
0
    //アイテム画像ファイルを拾ってくる。
    private void LoadItem(string path)
    {
        byte[] buffer;
        try
        {
            //閲覧するエントリ
            string extractFile = path;
            ICSharpCode.SharpZipLib.Zip.ZipFile zf;
            //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)
            {
                //pngファイルの場合
                if (path.Substring(path.Length - 4) == ".png" || path.Substring(path.Length - 4) == ".PNG" || path.Substring(path.Length - 4) == ".jpg" || path.Substring(path.Length - 4) == ".JPG")
                {
                    //閲覧するZIPエントリのStreamを取得
                    Stream fs = zf.GetInputStream(ze);
                    buffer = ReadBinaryData(fs);//bufferにbyte[]になったファイルを読み込み

                    // 画像を取り出す

                    //byteからTexture2D作成
                    Texture2D texture = new Texture2D(1, 1);
                    texture.LoadImage(buffer);
                    obj6.GetComponent <Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    //閉じる
                    fs.Close();
                }
            }
            //閉じる
            zf.Close();
        }
        catch
        {
        }
    }
Exemplo n.º 49
0
    //startのタイミングでフリーイベントの一覧表を取得し、条件を満たしているものはボタンを作成(Mapシーン限定)
    private void GetFreeIvent(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();
                text = text.Replace("[system]任意イベント", "[system]任意イベントCS");
                // 読み込んだ目次テキストファイルからstring配列を作成する
                mapData = text.Split('\n');
                //閉じる
                sr.Close();
                reader.Close();
            }
            else
            {
                SceneManager.LoadScene("TitleScene");
            }
            //閉じる
            zf.Close();
        }
        catch
        {
        }
    }
Exemplo n.º 50
0
        public static void UncompressZip(string archiveFile, string directory)
        {
            using (var fileStream = File.OpenRead(archiveFile))
                using (var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fileStream))
                {
                    var entries = zipFile.Cast <ZipEntry>().Where(x => !x.IsDirectory);
                    foreach (var entry in entries)
                    {
                        var file = PathConstruction.Combine(directory, entry.Name);
                        FileSystemTasks.EnsureExistingParentDirectory(file);

                        using (var entryStream = zipFile.GetInputStream(entry))
                            using (var outputStream = File.Open(file, FileMode.Create))
                            {
                                entryStream.CopyTo(outputStream);
                            }
                    }
                }

            Logger.Info($"Uncompressed '{archiveFile}' to '{directory}'.");
        }
Exemplo n.º 51
0
        public byte[] UnZipData(byte[] inputData)
        {
            try
            {
                using (MemoryStream ms = new MemoryStream(inputData))
                {
                    using (ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(ms))
                    {
                        ZipEntry zipEntry = zipFile[0];
                        byte[]   outData  = new byte[zipEntry.Size];
                        var      stream   = zipFile.GetInputStream(zipEntry);
                        stream.Read(outData, 0, outData.Length);
                        return(outData);
                    }
                }
            }
            catch (System.Exception)
            {
            }

            return(null);
        }
Exemplo n.º 52
0
    public void GetStartPoint()
    {
        string[] strs;
        //閲覧するエントリ
        string extractFile = "[system]command1[system]PC版スタート地点[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);

        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配列を作成する
            strs = text.Split('\n');
            strs = strs[1].Substring(12).Replace("\r", "").Replace("\n", "").Split(',');
            //閉じる
            sr.Close();
            reader.Close();
        }
        else
        {
            strs    = new string[2];
            strs[0] = "35.010348"; strs[1] = "135.768738";
        }
        //閉じる
        zf.Close();
        latitude = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
    }
Exemplo n.º 53
0
    private void FileSearchLoop(ICSharpCode.SharpZipLib.Zip.ZipEntry ze, ICSharpCode.SharpZipLib.Zip.ZipFile zf)
    {
        bool next;

        if (ze.Name.Length > 4)
        {
            if (ze.Name.Substring(ze.Name.Length - 4) == ".txt")
            {
                //閲覧する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();
                foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze2 in zf)
                {
                    if (text.Contains(ze2.Name))
                    {
                        string tmpStr = ze2.Name;
                        next = true;
                        foreach (string str in tmpList)
                        {
                            if (str == ze2.Name)
                            {
                                next = false;
                            }
                        }
                        tmpList.Add(tmpStr);
                        if (next == true)
                        {
                            FileSearchLoop(ze2, zf);
                        }
                    }
                }//再帰でzeから繋がるツリーを総探査する。
            }
        }
    }
Exemplo n.º 54
0
    public void SetIvent()
    {
        string[] strs;
        string   passtmp = "";

        try
        {
            if (selectNum > 0)
            {
                FirstPlace.SetActive(false);
                IventMake.SetActive(true);
                strs = mapData[selectNum].Replace("\r", "").Replace("\n", "").Split(',');
                if (strs[10].Contains(" [system]任意イベント"))
                {
                    PLIventToggle.GetComponent <Toggle>().isOn = true; strs[10] = strs[10].Replace(" [system]任意イベント", "");
                }
                else
                {
                    PLIventToggle.GetComponent <Toggle>().isOn = false;
                }
                inputField[0].text  = strs[11].Substring(0, strs[11].Length - 4).Replace("[system]", "");
                inputField[1].text  = strs[0];
                inputField[2].text  = strs[1];
                inputField[3].text  = strs[2];
                inputField[4].text  = strs[3];
                inputField[5].text  = strs[4];
                inputField[6].text  = strs[5];
                inputField[7].text  = strs[6];
                inputField[8].text  = strs[7];
                inputField[9].text  = strs[8];
                inputField[10].text = strs[9];
                inputField[11].text = strs[10];
                latitude            = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
            }
            if (selectNum == 0)
            {
                FirstPlace.SetActive(true);
                IventMake.SetActive(false);
                //閲覧するエントリ
                string extractFile = "[system]command1[system]PC版スタート地点[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);

                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配列を作成する
                    strs = text.Split('\n');
                    strs = strs[1].Substring(12).Replace("\r", "").Replace("\n", "").Split(',');
                    //閉じる
                    sr.Close();
                    reader.Close();
                    mapData[selectNum] = ",,,,,,,,,,,[system]PC版スタート地点[system].txt";
                }
                else
                {
                    strs               = new string[2];
                    strs[0]            = "35.010348"; strs[1] = "135.768738";
                    mapData[selectNum] = ",,,,,,,,,,,[system]PC版スタート地点[system].txt";
                }

                ICSharpCode.SharpZipLib.Zip.ZipEntry ze2 = zf.GetEntry("[system]password[system].txt");
                if (ze2 != null)
                {
                    //閲覧する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"));
                    // テキストを取り出す
                    passtmp = sr.ReadToEnd();

                    //閉じる
                    sr.Close();
                    reader.Close();
                }

                //閉じる
                zf.Close();
                GameObject.Find("ScenarioNameInput").GetComponent <InputField>().text = System.IO.Path.GetFileNameWithoutExtension(PlayerPrefs.GetString("進行中シナリオ", ""));
                GameObject.Find("PassWordInput").GetComponent <InputField>().text     = passtmp;
                inputField[12].text = strs[0];
                inputField[13].text = strs[1];
                latitude            = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
            }
        }
        catch
        {
        }
    }
        public void ExtractZipFile(string archivePath, string password, string outFolder)
        {
            using (Stream fsInput = File.OpenRead(archivePath))
                using (var zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fsInput))
                {
                    if (!String.IsNullOrEmpty(password))
                    {
                        // AES encrypted entries are handled automatically
                        zf.Password = password;
                    }
                    long fileCt = zf.Count;
                    int  ct     = 0;
                    foreach (ZipEntry zipEntry in zf)
                    {
                        ct++;
                        this.DownloadPercentage = (int)((ct / fileCt) * 20M);
                        if (!zipEntry.IsFile)
                        {
                            // Ignore directories
                            continue;
                        }
                        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.
                        var fullZipToPath = Path.Combine(outFolder, entryFileName);
                        if (entryFileName.Equals("sqrl.db", StringComparison.OrdinalIgnoreCase) && File.Exists(entryFileName))
                        {
                            continue;
                        }
                        var directoryName = Path.GetDirectoryName(fullZipToPath);
                        if (directoryName.Length > 0)
                        {
                            if (!Directory.Exists(directoryName))
                            {
                                Directory.CreateDirectory(directoryName);
                                if (this.platform == "WINDOWS")
                                {
                                    SetFileAccess(directoryName);
                                }
                            }
                        }

                        // 4K is optimum
                        var buffer = new byte[4096];

                        // 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 (var zipStream = zf.GetInputStream(zipEntry))
                            using (Stream fsOutput = File.Create(fullZipToPath))
                            {
                                StreamUtils.Copy(zipStream, fsOutput, buffer);
                                if (this.platform == "WINDOWS")
                                {
                                    SetFileAccess(fullZipToPath);
                                }
                            }
                    }
                }
        }
Exemplo n.º 56
0
        /// <summary>
        /// Extracts the first image from a zip file.
        /// </summary>
        /// <param name="archiveFilenameIn">
        /// The archive filename in.
        /// </param>
        /// <param name="outFolder">
        /// The out folder.
        /// </param>
        public static IMediaModel ExtractZipFileFirstImage(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel)
        {
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
            try
            {
                FileStream fs = File.OpenRead(argExistingMediaModel.MediaStorageFilePath);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;           // Ignore directories
                    }

                    string entryFileName = zipEntry.Name;

                    // check for image TODO do proper mimetype mapping. See https://github.com/samuelneff/MimeTypeMap
                    if (SharedSharp.Common.SharedSharpGeneral.MimeMimeTypeGet(CommonRoutines.MimeFileContentTypeGet(Path.GetExtension(zipEntry.Name))) != "image")
                    {
                        continue;
                    }
                    else
                    {
                        // set extension
                        argNewMediaModel.OriginalFilePath = Path.ChangeExtension(argNewMediaModel.OriginalFilePath, Path.GetExtension(zipEntry.Name));

                        // Unzip the file
                        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(System.IO.Path.Combine(argCurrentDataFolder.FullName, argNewMediaModel.OriginalFilePath)))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }

                        // exit early
                        return(argNewMediaModel);
                    }
                }

                fs.Close();

                // Exit
                return(new MediaModel());
            }
            catch (DirectoryNotFoundException ex)
            {
                ErrorInfo t = new ErrorInfo("Directory not found when trying to create image from ZIP file")
                {
                    { "Original ID", argExistingMediaModel.Id },
                    { "Original File", argExistingMediaModel.MediaStorageFilePath },
                    { "Clipped Id", argNewMediaModel.Id },
                    { "New path", "pdfimage" }
                };

                App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t);

                return(new MediaModel());
            }
            catch (Exception ex)
            {
                ErrorInfo t = new ErrorInfo("Exception when trying to create image from ZIP file")
                {
                    { "Original ID", argExistingMediaModel.Id },
                    { "Original File", argExistingMediaModel.MediaStorageFilePath },
                    { "Clipped Id", argNewMediaModel.Id }
                };

                App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t);

                return(new MediaModel());
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Exemplo n.º 57
0
 public Stream Open()
 {
     return(Handle.GetInputStream(Entry));
 }
Exemplo n.º 58
0
    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);
        }
    }
Exemplo n.º 59
0
    //目次ファイルを読み込む。
    private void LoadMapData(string path)
    {
        string str2;

        //string[] strs;
        try
        {
            //閲覧するエントリ
            string extractFile = path;

            //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"));
                    // テキストを取り出す
                    string text = sr.ReadToEnd();

                    // 読み込んだ目次テキストファイルからstring配列を作成する
                    mapData.AddRange(text.Split('\n'));
                    //閉じる
                    sr.Close();
                    reader.Close();
                    mapData.RemoveAt(mapData.Count - 1);//最終行は[END]なので除去。
                    //イベントをボタンとして一覧に放り込む。
                    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);
                    }
                }
                else
                {
                    GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "TitleScene");
                }
            }
            catch { }

            ze = zf.GetEntry("[system]command1[system]PC版スタート地点[system].txt");

            /*
             * 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"));
             *  // テキストを取り出す
             *  string text = sr.ReadToEnd();
             *
             *  // 読み込んだ目次テキストファイルからstring配列を作成する
             *  strs = text.Split('\n');
             *  strs = strs[1].Substring(12).Replace("\r", "").Replace("\n", "").Split(',');
             *  //閉じる
             *  sr.Close();
             *  reader.Close();
             *  latitude = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
             *  objIB[0].GetComponentInChildren<Text>().text = "PC版スタート地点 緯:" + latitude.ToString() + ",経:" + longitude.ToString();
             * }
             * }
             * catch { }
             */

            //閉じる
            zf.Close();

            str2 = "";
            for (int i = 0; i < mapData.Count; i++)
            {
                if (mapData[i].Replace("\n", "").Replace("\r", "") == "")
                {
                    continue;
                }
                str2 = str2 + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n";
            }
            undoList.Add(str2);
            undoListNum = undoList.Count - 1;
        }
        catch
        {
            GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "TitleScene");
        }
    }
Exemplo n.º 60
0
    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();
    }