public GetEntry ( string name ) : |
||
name | string | /// The name to find. May contain directory components separated by slashes ('/'). /// |
return |
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); } }
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)); }
/// <summary> /// Compares all idml's in outputPath to make sure the content.xml and styles.xml are the same /// </summary> public static void AreEqual(string expectFullName, string outputFullName, string msg) { using (var expFl = new ZipFile(expectFullName)) { var outFl = new ZipFile(outputFullName); foreach (ZipEntry zipEntry in expFl) { //TODO: designmap.xml should be tested but \\MetadataPacketPreference should be ignored as it contains the creation date. if (!CheckFile(zipEntry.Name,"Stories,Spreads,Resources,MasterSpreads")) continue; if (Path.GetExtension(zipEntry.Name) != ".xml") continue; string outputEntry = new StreamReader(outFl.GetInputStream(outFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd(); string expectEntry = new StreamReader(expFl.GetInputStream(expFl.GetEntry(zipEntry.Name).ZipFileIndex)).ReadToEnd(); XmlDocument outputDocument = new XmlDocument(); outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver(); outputDocument.LoadXml(outputEntry); XmlDocument expectDocument = new XmlDocument(); outputDocument.XmlResolver = FileStreamXmlResolver.GetNullResolver(); expectDocument.LoadXml(expectEntry); XmlDsigC14NTransform outputCanon = new XmlDsigC14NTransform(); outputCanon.Resolver = new XmlUrlResolver(); outputCanon.LoadInput(outputDocument); XmlDsigC14NTransform expectCanon = new XmlDsigC14NTransform(); expectCanon.Resolver = new XmlUrlResolver(); expectCanon.LoadInput(expectDocument); Stream outputStream = (Stream)outputCanon.GetOutput(typeof(Stream)); Stream expectStream = (Stream)expectCanon.GetOutput(typeof(Stream)); string errMessage = string.Format("{0}: {1} doesn't match", msg, zipEntry.Name); Assert.AreEqual(expectStream.Length, outputStream.Length, errMessage); FileAssert.AreEqual(expectStream, outputStream, errMessage); } } }
public 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); } }
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(); } }; }
/// <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(); } } }
public static void LoadPack(string packDir) { Dictionary<string, Dictionary<ushort, string>> allTextMap; using (var z = new ZipFile(Path.Combine(packDir, "text.zip"))) { using (var texter = new StreamReader(z.GetInputStream(z.GetEntry("text.csv")), Encoding.UTF8)) { allTextMap = CSV.ParseCSVText(texter); } } var byterList = new List<BinaryReader>(); var zipFiles = new List<ZipFile>(); foreach (var f in Directory.GetFiles(packDir, "*.zip")) { var name = Path.GetFileNameWithoutExtension(f); if (name != null && !name.Equals("text")) { var z = new ZipFile(f); zipFiles.Add(z); var byter = new BinaryReader(z.GetInputStream(z.GetEntry(name))); byterList.Add(byter); } } Processor(new Stream(byterList, allTextMap)); foreach (var z in zipFiles) { z.Close(); } }
/// <summary> /// 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); } } }
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; } } }
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); } }
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\">")); }
public void PushPasswordButton() { string pass; string text = ""; pass = pass2Obj.GetComponent <InputField>().text; try { //閲覧するエントリ string extractFile = "[system]password[system].txt"; //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; //展開するエントリを探す ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile); try { if (ze != null) { //閲覧するZIPエントリのStreamを取得 System.IO.Stream reader = zf.GetInputStream(ze); //文字コードを指定してStreamReaderを作成 System.IO.StreamReader sr = new System.IO.StreamReader( reader, System.Text.Encoding.GetEncoding("UTF-8")); // テキストを取り出す text = sr.ReadToEnd(); //閉じる sr.Close(); reader.Close(); } } catch { } //閉じる zf.Close(); } catch { GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "シナリオファイルに異常があります。"; return; } if (text == "" || text == pass) { GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "MapScene"); } else { GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "パスワードが違います。"; return; } }
public static void Process( ZipFile zip, ChartRenderingJob chart) { TemporaryDataSource tds = new TemporaryDataSource(){ ms = new MemoryStream()}; var currentEntry = zip.GetEntry(chart.TemplatePath); using( var input = zip.GetInputStream(currentEntry)) { ChartWriter.RenderChart(chart,input,tds.ms); } zip.BeginUpdate(); zip.Add(tds, currentEntry.Name,currentEntry.CompressionMethod,currentEntry.IsUnicodeText); zip.CommitUpdate(); }
public async Task Load(string filePath) { var fiSource = new FileInfo(filePath); using (var fs = new FileStream(fiSource.FullName, FileMode.Open, FileAccess.Read)) using (var zf = new ZipFile(fs)) { if (ContainsAudioVisualisation) { using (var stream = zf.GetInputStream(zf.GetEntry(ThemePackConsts.AudioVisualisationName))) { _audioVisualisationPlugin = await Task.Run(() => AudioVisualisationPluginHelper.FromStream(stream)); } } if (ContainsBackground) { var path = "HurricaneBackground" + BackgroundName; var backgroundZipEntry = zf.GetEntry(BackgroundName); using (var zipStream = zf.GetInputStream(backgroundZipEntry)) { var buffer = new byte[4096]; var file = new FileInfo(path); if (file.Exists) file.Delete(); using (var streamWriter = File.Create(file.FullName)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } _backgroundPath = file.FullName; } } if (ContainsAppTheme) { using (var stream = zf.GetInputStream(zf.GetEntry(ThemePackConsts.AppThemeName))) { _appThemeResourceDictionary = (ResourceDictionary)XamlReader.Load(stream); } } if (ContainsAccentColor) { using (var stream = zf.GetInputStream(zf.GetEntry(ThemePackConsts.AccentColorName))) { _accentColorResourceDictionary = (ResourceDictionary)XamlReader.Load(stream); } } } }
/// <summary> /// Load the data for the given filename. /// </summary> public byte[] Load(string fileName) { using (var file = new ZipFile(path)) { var entry = file.GetEntry(fileName); if (entry == null) return null; using (var stream = file.GetInputStream(entry)) { var data = new byte[entry.Size]; stream.Read(data, 0, data.Length); return data; } } }
//目次ファイルを読み込み、進行度に合わせてファイルを拾ってくる。 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]; } }
public void ScenarioFileCheck(int num, ICSharpCode.SharpZipLib.Zip.ZipFile zf) { string[] strs; strs = mapData[num].Replace("\r", "").Replace("\n", "").Split(',');//strs[11]がシナリオパス try { //展開するエントリを探す ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(strs[11]); //参照先のファイルがあるか調べる。なかったら(未)をつける。 if (ze == null) { objIB[num].GetComponentInChildren <Text>().text = "(未)" + objIB[num].GetComponentInChildren <Text>().text; } } catch { } }
public void GH221() { // This is a perfectly fine file, written by 'file-roller', but // SharpZipLib can choke on it because it's not properly handling // the headers properly. See GH #221. string file = Path.Combine(TestData.DataDir(), "gh221.zip"); var zipfile = new ZipFile(file); var entry = zipfile.GetEntry("221.txt"); string version = string.Format("{0}", entry.Version); Assert.DoesNotThrow(delegate { zipfile.GetInputStream(entry); }, "zip-entry format {0} (788 is our bug)", version); }
// ProjectS 中,一个Spine内可以有多个共享部件的角色,它们以动画名称前缀区分 // json 解析是从 Spine-Runtime 里拿过来的 public static List<String> GetWarriorNames(String spineName) { String resDir = UserConfigManager.Instance.Config.ResDir; string zipPath = System.IO.Path.Combine(resDir, "spine/" + spineName + ".zip"); FileInfo zipFInfo = new FileInfo(zipPath); if (!zipFInfo.Exists) return new List<String>(); ZipFile zf = new ZipFile(zipPath); ZipEntry jsonEntry = zf.GetEntry(spineName + ".json"); Stream jsonStream = zf.GetInputStream(jsonEntry); var root = new Dictionary<String, Object>(); using (TextReader reader = new StreamReader(jsonStream)) { root = Json.Deserialize(reader) as Dictionary<String, Object>; } if (root == null) throw new Exception(String.Format("Spine json 文件错误: {0} {1}", spineName, zipPath)); List<String> result = new List<string>(); if (root.ContainsKey("animations")) { foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["animations"]) { int dashPos = entry.Key.IndexOf('_'); if (dashPos != -1) { string actorName = entry.Key.Substring(0, dashPos); if (!result.Contains(actorName)) { result.Add(actorName); } } } } return result; }
/// <summary> /// Commits the updates. /// </summary> /// <remarks>Documented by Dev03, 2009-07-20</remarks> public void CommitUpdates() { ZipFile zipFile = null; try { zipFile = new ZipFile(file.FullName); zipFile.UseZip64 = UseZip64.Off; // AAB-20090720: Zip64 caused some problem when modifing the archive (ErrorReportHandler.cs) - Zip64 is required to bypass the 4.2G limitation of the original Zip format (http://en.wikipedia.org/wiki/ZIP_(file_format)) ZipEntry errorReport = zipFile.GetEntry(Resources.ERRORFILE_NAME); MemoryStream stream = new MemoryStream(); using (Stream s = GetZipStream(errorReport, zipFile)) { XmlDocument doc = new XmlDocument(); using (StreamReader reader = new StreamReader(s, Encoding.Unicode)) { doc.LoadXml(reader.ReadToEnd()); } foreach (Dictionary<string, string> value in values) { XmlElement xE = doc.CreateElement(value["nodeName"]); xE.InnerText = value["value"].Trim(); XmlNode parentNode = doc.SelectSingleNode(value["parentPath"]); if (parentNode == null) return; parentNode.AppendChild(xE); } doc.Save(stream); } ZipData data = new ZipData(stream); zipFile.BeginUpdate(); zipFile.Delete(errorReport); //delete first! zipFile.CommitUpdate(); zipFile.BeginUpdate(); zipFile.Add(data, errorReport.Name); zipFile.CommitUpdate(); } finally { if (zipFile != null) zipFile.Close(); } }
//アイテム画像ファイルを拾ってくる。 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 { } }
//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 { } }
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]); }
private static void ProcessZip(object data, ZipFile zipFile) { zipFile.BeginUpdate(); var document = ""; var entry = zipFile.GetEntry(DocumentXmlPath); if (entry == null) { throw new Exception(string.Format("Can't find {0} in template zip", DocumentXmlPath)); } using (var s = zipFile.GetInputStream(entry)) using (var reader = new StreamReader(s, Encoding.UTF8)) { document = reader.ReadToEnd(); } var newDocument = ParseTemplate(document, data); zipFile.Add(new StringStaticDataSource(newDocument), DocumentXmlPath, CompressionMethod.Deflated, true); zipFile.CommitUpdate(); }
public static void savePhotoPositions(Form ownerForm, string folderOrZipName) { if (Project.photoPositionsDonotwrite) { return; } XmlDocument xmlDoc = makePhotoPositionsXmlDoc(); if (AllFormats.isZipFile(folderOrZipName)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Zip file not found: " + folderOrZipName); return; } string ppfName = folderOrZipName + "|" + Project.PHOTO_POSITIONS_FILE_NAME; string message = "Confirm: will write photo positions to " + ppfName + "\n\nDo you want to create/overwrite the file (inside the ZIP archive)?"; if (!Project.photoPositionsAsk || Project.YesNoBox(ownerForm, message)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Failed to open Zip file: " + folderOrZipName); return; } using (ZipFile zip = new ZipFile(folderOrZipName)) { ZipEntry entry = zip.GetEntry(Project.PHOTO_POSITIONS_FILE_NAME); if (entry == null) { LibSys.StatusBar.Trace("IP: creating photo positions entry: " + folderOrZipName + "|" + Project.PHOTO_POSITIONS_FILE_NAME); zip.BeginUpdate(); } else { string fileName = entry.Name; LibSys.StatusBar.Trace("IP: existing photo positions entry: " + folderOrZipName + "|" + fileName); zip.BeginUpdate(); zip.Delete(entry); } StringMemoryDataSource m = new StringMemoryDataSource(xmlDoc.OuterXml); zip.Add(m, Project.PHOTO_POSITIONS_FILE_NAME); zip.CommitUpdate(); } } } else { if (!Directory.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Folder not found: " + folderOrZipName); return; } string ppfName = Path.Combine(folderOrZipName, Project.PHOTO_POSITIONS_FILE_NAME); try { if (File.Exists(ppfName)) { LibSys.StatusBar.Trace("IP: existing photo positions file: " + ppfName); } else { LibSys.StatusBar.Trace("IP: creating photo positions file: " + ppfName); } xmlDoc.Save(ppfName); } catch (Exception e) { LibSys.StatusBar.Error("DlgPhotoManager:savePhotoPositions() " + e.Message); } } }
public Pixbuf LoadThumbnail(string filename, int maxWidth, int maxHeight) { ZipFile file = new ZipFile (filename); ZipEntry ze = file.GetEntry ("Thumbnails/thumbnail.png"); // The ORA specification requires that all files will have a // thumbnail that is less than 256x256 pixels, so don't bother // with scaling the preview. Pixbuf p = new Pixbuf (file.GetInputStream (ze)); file.Close (); return p; }
/// <summary> /// Gets the value. /// </summary> /// <param name="path">The path z.B. "Exception/Message".</param> /// <returns></returns> /// <remarks>Documented by Dev07, 2009-07-16</remarks> public string GetValue(string path) { ZipFile zipFile = null; try { zipFile = new ZipFile(file.FullName); ZipEntry errorReport = zipFile.GetEntry(Resources.ERRORFILE_NAME); using (Stream s = GetZipStream(errorReport, zipFile)) { XmlDocument doc = new XmlDocument(); using (StreamReader reader = new StreamReader(s, Encoding.Unicode)) { doc.LoadXml(reader.ReadToEnd()); } if (!path.StartsWith("/")) path = "//" + path; return doc.SelectSingleNode(path).InnerText; } } finally { if (zipFile != null) zipFile.Close(); } }
private void ExtensionBrowseButton_Click(object sender, EventArgs e) { using (var extensionBrowser = new OpenFileDialog()) { extensionBrowser.CheckFileExists = true; extensionBrowser.Filter = TextHelper.GetString("Info.AneFilter"); extensionBrowser.InitialDirectory = _propertiesFilePath; if (extensionBrowser.ShowDialog(this) == DialogResult.OK) { ZipFile zFile; try { zFile = new ZipFile(extensionBrowser.FileName); } catch (Exception ex) { String msg = TextHelper.GetString("Info.CouldNotLoadANE") + "\n" + ex.Message; ErrorManager.ShowWarning(msg, null); return; } var entry = zFile.GetEntry("META-INF/ANE/extension.xml"); if (entry == null) { String msg = TextHelper.GetString("Info.ANEDescFileNotFound"); ErrorManager.ShowWarning(msg, null); return; } byte[] buffer = UnzipFile(zFile, entry); string extensionId = null; using (var stream = new MemoryStream(buffer)) { using (var reader = XmlReader.Create(stream)) { reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element) continue; if (reader.Name == "id") { extensionId = reader.ReadInnerXml(); break; } } } } if (extensionId == null) { String msg = TextHelper.GetString("Info.ExtensionIDNotFound"); ErrorManager.ShowWarning(msg, null); return; } PropertyManager.AirExtension extension = null; // We look for the extension in case it is already added, and modify its path, maybe FD is missing the external library entry and the user //wants to add it. foreach (var existingExtension in _extensions) { if (existingExtension.ExtensionId == extensionId) extension = existingExtension; break; } if (extension == null) { extension = new PropertyManager.AirExtension() { ExtensionId = extensionId, IsValid = true }; _extensions.Add(extension); //I don't validation and selection is needed in this case var extensionListItem = new ListViewItem(extension.ExtensionId); ExtensionsListView.Items.Add(extensionListItem); } extension.Path = extensionBrowser.FileName; } } }
public void PasteButton() { string str = ""; string[] strs; string copyfile = ""; string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp.txt"; if (objBGM.GetComponent <BGMManager>().copyMapString == "") { GameObject.Find("Error").GetComponent <Text>().text = "先にコピー元を選んでください。"; StartCoroutine(ErrorWait()); return; } if (selectNum < 0) { GameObject.Find("Error").GetComponent <Text>().text = "貼り付け先(そのイベントの後ろに挿入されます)が選択されていません。"; StartCoroutine(ErrorWait()); return; } List <string> strList = new List <string>(); strList.AddRange(undoList[undoListNum].Replace("\r", "").Split('\n')); //コピーするイベント名の取得 strs = objBGM.GetComponent <BGMManager>().copyMapString.Replace("\r", "").Split('\n'); //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", "")); zf.Password = Secret.SecretString.zipPass; for (int j = 0; j < strs.Length; j++) { string[] strs2; strs2 = strs[j].Split(','); copyfile = strs2[11].Replace("\r", "").Replace("\n", ""); try { ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(copyfile); tmpList.Clear(); //コピーファイルのリスト化 FileSearchLoop(ze, zf); //ファイルのコピー for (int i = 0; i < tmpList.Count; i++) { ICSharpCode.SharpZipLib.Zip.ZipEntry ze2 = zf.GetEntry(tmpList[i]); if (ze2.Name.Length > 4 && ze2.Name.Substring(ze2.Name.Length - 4) == ".txt") { //閲覧するZIPエントリのStreamを取得 System.IO.Stream reader = zf.GetInputStream(ze2); //文字コードを指定してStreamReaderを作成 System.IO.StreamReader sr = new System.IO.StreamReader( reader, System.Text.Encoding.GetEncoding("UTF-8")); // テキストを取り出す string text = sr.ReadToEnd(); for (int k = 0; k < 9999; k++) { for (int x = 0; x < strList.Count; x++) { if (strList[x].Contains(copyfile.Substring(0, copyfile.Length - 4) + "copy" + k.ToString() + ".txt")) { break; } if (x == strList.Count - 1) { copynum = k; goto e1; } } } e1: text = text.Replace(copyfile, copyfile.Substring(0, copyfile.Length - 4) + "copy" + copynum.ToString() + ".txt"); System.IO.File.WriteAllText(file, text); //ZIP内のエントリの名前を決定する string f = "dammyfile.txt"; f = System.IO.Path.GetFileName(tmpList[i].Replace(copyfile, copyfile.Substring(0, copyfile.Length - 4) + "copy" + copynum.ToString() + ".txt")); //ZipFileの更新を開始 zf.BeginUpdate(); //ZIP書庫に一時的に書きだしておいたファイルを追加する zf.Add(file, f); //ZipFileの更新をコミット zf.CommitUpdate(); } } } catch { } } //一時的に書きだしたtmp.txtを消去する。 System.IO.File.Delete(file); strList.InsertRange(selectNum + 1, CopyMake(objBGM.GetComponent <BGMManager>().copyMapString.Replace("\r", "").Split('\n'), strList)); mapData.Clear(); for (int i = 0; i < objIB.Count; i++) { Destroy(objIB[i]); } objIB.Clear(); // 読み込んだ目次テキストファイルからstring配列を作成する mapData.AddRange(strList); mapData.RemoveAt(mapData.Count - 1); //最後の行は空白なので消す //コマンドをボタンとして一覧に放り込む。 for (int i = 0; i < mapData.Count; i++) { objIB.Add(Instantiate(objIvent) as GameObject); objIB[i].transform.SetParent(parentObject.transform, false); objIB[i].GetComponentInChildren <Text>().text = MapDataToButton(mapData[i]); objIB[i].GetComponent <IventButton>().buttonNum = i; ScenarioFileCheck(i, zf); } zf.Close(); for (int i = 0; i < mapData.Count; i++) { str = str + mapData[i].Replace("\r", "").Replace("\n", "") + "\r\n"; } undoList.Add(str); undoListNum = undoList.Count - 1; selectNum = -1; multiSelect.Clear(); MakeMapDataFile(); }
public static void savePhotoParameters(Form ownerForm, string folderOrZipName) { if (Project.photoParametersDonotwrite) { return; } if (AllFormats.isZipFile(folderOrZipName)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Zip file not found: " + folderOrZipName); return; } string ppfName = folderOrZipName + "|" + Project.PHOTO_PARAM_FILE_NAME; string message = "Confirm: will write new Camera Time Shift to " + ppfName + "\n\nDo you want to create/overwrite the file (inside the ZIP archive)?"; if (!Project.photoParametersAsk || Project.YesNoBox(ownerForm, message)) { if (!File.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Failed to open Zip file: " + folderOrZipName); return; } XmlDocument xmlDoc = null; using (ZipFile zip = new ZipFile(folderOrZipName)) { ZipEntry entry = zip.GetEntry(Project.PHOTO_PARAM_FILE_NAME); if (entry == null) { LibSys.StatusBar.Trace("IP: creating photo parameters entry: " + folderOrZipName + "|" + Project.PHOTO_PARAM_FILE_NAME); xmlDoc = makePhotoParametersXmlDoc(); zip.BeginUpdate(); } else { string fileName = entry.Name; LibSys.StatusBar.Trace("IP: existing photo parameters entry: " + folderOrZipName + "|" + fileName); xmlDoc = new XmlDocument(); Stream stream = zip.GetInputStream(entry); using (StreamReader rdr = new StreamReader(stream)) { xmlDoc.LoadXml(rdr.ReadToEnd()); } editPhotoParametersXmlDoc(xmlDoc); zip.BeginUpdate(); zip.Delete(entry); } StringMemoryDataSource m = new StringMemoryDataSource(xmlDoc.OuterXml); zip.Add(m, Project.PHOTO_PARAM_FILE_NAME); lastPhotoParametersFileName = ppfName; zip.CommitUpdate(); } } } else { if (!Directory.Exists(folderOrZipName)) { Project.ErrorBox(ownerForm, "Folder not found: " + folderOrZipName); return; } string ppfName = Path.Combine(folderOrZipName, Project.PHOTO_PARAM_FILE_NAME); string message = "Confirm: will write new Camera Time Shift to " + ppfName + "\n\nDo you want to " + (File.Exists(ppfName) ? "overwrite" : "create") + " the file?"; if (!Project.photoParametersAsk || Project.YesNoBox(ownerForm, message)) { try { if (File.Exists(ppfName)) { LibSys.StatusBar.Trace("IP: existing photo parameters file: " + ppfName); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(ppfName); editPhotoParametersXmlDoc(xmlDoc); xmlDoc.Save(ppfName); lastPhotoParametersFileName = ppfName; } else { LibSys.StatusBar.Trace("IP: creating photo parameters file: " + ppfName); XmlDocument xmlDoc = makePhotoParametersXmlDoc(); xmlDoc.Save(ppfName); lastPhotoParametersFileName = ppfName; } } catch (Exception e) { LibSys.StatusBar.Error("DlgPhotoManager:savePhotoParameters() " + e.Message); } } } }
public void Import(LayerManager layers, string fileName) { ZipFile file = new ZipFile (fileName); XmlDocument stackXml = new XmlDocument (); stackXml.Load (file.GetInputStream (file.GetEntry ("stack.xml"))); XmlElement imageElement = stackXml.DocumentElement; int width = int.Parse (imageElement.GetAttribute ("w")); int height = int.Parse (imageElement.GetAttribute ("h")); XmlElement stackElement = (XmlElement) stackXml.GetElementsByTagName ("stack")[0]; XmlNodeList layerElements = stackElement.GetElementsByTagName ("layer"); if (layerElements.Count == 0) throw new XmlException ("No layers found in OpenRaster file"); layers.Clear (); PintaCore.History.Clear (); layers.DestroySelectionLayer (); PintaCore.Workspace.ImageSize = new Size (width, height); PintaCore.Workspace.CanvasSize = new Gdk.Size (width, height); for (int i = 0; i < layerElements.Count; i++) { XmlElement layerElement = (XmlElement) layerElements[i]; int x = int.Parse (GetAttribute (layerElement, "x", "0")); int y = int.Parse (GetAttribute (layerElement, "y", "0")); string name = GetAttribute (layerElement, "name", string.Format ("Layer {0}", i)); try { // Write the file to a temporary file first // Fixes a bug when running on .Net ZipEntry zf = file.GetEntry (layerElement.GetAttribute ("src")); Stream s = file.GetInputStream (zf); string tmp_file = System.IO.Path.GetTempFileName (); using (Stream stream_out = File.Open (tmp_file, FileMode.OpenOrCreate)) { byte[] buffer = new byte[2048]; while (true) { int len = s.Read (buffer, 0, buffer.Length); if (len > 0) stream_out.Write (buffer, 0, len); else break; } } Layer layer = layers.CreateLayer (name, width, height); layers.Insert (layer, 0); layer.Opacity = double.Parse (GetAttribute (layerElement, "opacity", "1"), GetFormat ()); using (Pixbuf pb = new Pixbuf (tmp_file)) { using (Context g = new Context (layer.Surface)) { CairoHelper.SetSourcePixbuf (g, pb, x, y); g.Paint (); } } try { File.Delete (tmp_file); } catch { } } catch { MessageDialog md = new MessageDialog (PintaCore.Chrome.MainWindow, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Could not import layer \"{0}\" from {0}", name, file); md.Title = "Error"; md.Run (); md.Destroy (); } } file.Close (); }
public static void unzipOneFile(string zipfilePath, string entryName, string plainfilePath) { if (!File.Exists(zipfilePath)) { throw new Exception("failed to open Zip " + zipfilePath); } using (ZipFile zip = new ZipFile(zipfilePath)) { ZipEntry zipEntry = zip.GetEntry(entryName); if (zipEntry != null) { Stream zipEntryStream = zip.GetInputStream(zipEntry); FileStream fileStream = new FileStream(plainfilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); Project.CopyStream(zipEntryStream, fileStream); fileStream.Close(); zipEntryStream.Close(); } else { LibSys.StatusBar.Trace("IP: " + entryName + " -- NOT FOUND in archive " + zipfilePath); } } GC.Collect(); }
public static void DeversionBackupFile(string inputFile, string outputFile, bool verbose) { WriteLineToConsoleIfVerbose("Reading input file (" + inputFile + ")...", verbose); ZipFile zip = new ZipFile(inputFile); WriteLineToConsoleIfVerbose("Finding dump script...", verbose); ZipEntry entry = zip.GetEntry("temp\\users_pgsql_data.dat"); byte[] bytes; WriteLineToConsoleIfVerbose("Reading data...", verbose); using (var s = zip.GetInputStream(entry)) { bytes = new byte[entry.Size]; StreamUtils.ReadFully(s, bytes); } string file = Encoding.ASCII.GetString(bytes); int startIndex = 0; WriteLineToConsoleIfVerbose("Replacing config info...", verbose); //remove first 40 lines for (int i = 0; i < 38; i++) { startIndex = file.IndexOf("\n", startIndex + 1, file.Length - startIndex - 1); } file = file.Remove(0, startIndex); file = file.Insert(0, _replacementText); startIndex = 0; WriteLineToConsoleIfVerbose("Appending 'WITHOUT OIDS' to CREATE TABLE statements...", verbose); while (true) { int indexOf = file.IndexOf("CREATE TABLE", startIndex, file.Length - startIndex); if (indexOf < 0) { break; } startIndex = indexOf; int nextIndexOf = file.IndexOf(";", startIndex, file.Length - startIndex); file = file.Insert(nextIndexOf, " WITHOUT OIDS"); startIndex = nextIndexOf; } WriteLineToConsoleIfVerbose("Creating output file (" + outputFile + ")...", verbose); byte[] newBytes = Encoding.ASCII.GetBytes(file); MemoryStream ms = new MemoryStream(newBytes); FileStream fs = new FileStream(outputFile, FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.UseZip64 = UseZip64.Off; zipStream.SetLevel(3); //0-9, 9 being the highest level of compression //ZipEntry temp = new ZipEntry("temp/"); //zipStream.PutNextEntry(temp); ZipEntry newEntry = new ZipEntry("temp/users_pgsql_data.dat"); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); WriteLineToConsoleIfVerbose("Copying data to output stream...", verbose); StreamUtils.Copy(ms, zipStream, new byte[4096]); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream. fs.Position = 0; fs.Close(); zip.Close(); WriteLineToConsoleIfVerbose("Done!", verbose); }
private string DetectModelFromTranspoderDatabase(ZipFile zip) { var entry = zip.GetEntry("TransponderDatabase.dat"); if (entry == null) return null; var size = entry.Size - 4; var candidates = ""; if (size%49 == 0) candidates += "B"; if (size%45 == 0) candidates += "CDE"; return candidates; }
//目次ファイルを読み込む。 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"); } }
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 { } }
/// <summary> /// returns a short message to be displayed in dialog "progress" area /// </summary> /// <param name="folderPath"></param> /// <returns></returns> public static string readPhotoParameters(string folderPath, out bool hasFoundFile) { string ret = ""; lastPhotoParametersFileName = null; hasFoundFile = false; bool isZip = AllFormats.isZipFile(folderPath); string ppfName = isZip ? (folderPath + "|" + Project.PHOTO_PARAM_FILE_NAME) : Path.Combine(folderPath, Project.PHOTO_PARAM_FILE_NAME); string traceMsg = "reading photo parameters file: " + ppfName; try { XmlDocument xmlDoc = null; if (isZip) { if (!File.Exists(folderPath)) { LibSys.StatusBar.Error(traceMsg + " -- NOT FOUND"); throw new Exception("failed to open Zip " + folderPath); } using (ZipFile zip = new ZipFile(folderPath)) { ZipEntry entry = zip.GetEntry(Project.PHOTO_PARAM_FILE_NAME); if (entry != null) { string fileName = entry.Name; LibSys.StatusBar.Trace("IP: " + traceMsg); xmlDoc = new XmlDocument(); Stream stream = zip.GetInputStream(entry); using (StreamReader rdr = new StreamReader(stream)) { xmlDoc.LoadXml(rdr.ReadToEnd()); } } else { ret = "no " + Project.PHOTO_PARAM_FILE_NAME + " found in archive"; LibSys.StatusBar.Trace("IP: " + traceMsg + " -- NOT FOUND"); } } } else // not a zip file { if (File.Exists(ppfName)) { LibSys.StatusBar.Trace("IP: " + traceMsg); xmlDoc = new XmlDocument(); xmlDoc.Load(ppfName); } else { ret = "no " + Project.PHOTO_PARAM_FILE_NAME + " found in folder"; LibSys.StatusBar.Trace("IP: " + traceMsg + " -- NOT FOUND"); } } if (xmlDoc != null) { foreach (XmlNode nnode in xmlDoc.DocumentElement.ChildNodes) { if (nnode.Name.Equals("cameraSettings")) { foreach (XmlNode node in nnode) { string nodeName = node.Name; try { if (nodeName.Equals("cameraTimeShift")) { Project.photoTimeShiftFile = new TimeSpan((long)Convert.ToInt64(node.InnerText)); ret = "cameraTimeShift: " + Project.photoTimeShiftFile.TotalSeconds + " seconds"; LibSys.StatusBar.Trace("IP: " + ret); } else if (nodeName.Equals("cameraTimeZoneID")) { Project.photoTimeZoneIdFile = Convert.ToInt32(node.InnerText); ret = "Read from the " + Project.PHOTO_PARAM_FILE_NAME + " file in the " + (isZip ? "zipfile" : "folder") + " - Camera Time Zone ID: " + Project.photoTimeZoneIdFile + " (" + MyTimeZone.timeZoneById(Project.photoTimeZoneIdFile).ToString() + ")"; LibSys.StatusBar.Trace("IP: " + ret); } } catch (Exception ee) { // bad node - not a big deal... LibSys.StatusBar.Error("readPhotoParameters() node=" + nodeName + " " + ee.Message); } } } } hasFoundFile = true; lastPhotoParametersFileName = ppfName; Project.photoTimeShiftTypeCurrent = 2; // found file, use it! } } catch (Exception e) { LibSys.StatusBar.Trace(traceMsg); LibSys.StatusBar.Error("readPhotoParameters() " + e.Message); ret = e.Message; } lastPhotoParametersMessage = ret; return ret; }
public static FullSpriteSet FromShishiFile( string filename, System.ComponentModel.BackgroundWorker worker ) { Dictionary<string, Dictionary<string, List<string>>> manifest; List<AbstractSprite> sprites = new List<AbstractSprite>(); int tasks = 0; int tasksComplete = 0; using ( ZipFile zf = new ZipFile( filename ) ) { BinaryFormatter f = new BinaryFormatter(); manifest = f.Deserialize( zf.GetInputStream( zf.GetEntry( "manifest" ) ) ) as Dictionary<string, Dictionary<string, List<string>>>; foreach ( KeyValuePair<string, Dictionary<string, List<string>>> kvp in manifest ) { tasks += kvp.Value.Keys.Count * 3; } tasks += 1; foreach( string type in manifest.Keys ) { Type spriteType = Type.GetType( type ); ConstructorInfo constructor = spriteType.GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof( SerializedSprite ) }, null ); foreach( string name in manifest[type].Keys ) { List<string> filenames = manifest[type][name]; int size = filenames.Count; byte[][] bytes = new byte[size][]; worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, string.Format( "Extracting {0}", name ) ); ZipEntry entry = zf.GetEntry( string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Pixels", type, name ) ); byte[] pixels = new byte[entry.Size]; StreamUtils.ReadFully( zf.GetInputStream( entry ), pixels ); entry = zf.GetEntry( string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Palettes", type, name ) ); byte[] palettes = new byte[entry.Size]; StreamUtils.ReadFully( zf.GetInputStream( entry ), palettes ); entry = zf.GetEntry( string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}/{1}/Size", type, name ) ); byte[] sizeBytes = new byte[entry.Size]; StreamUtils.ReadFully( zf.GetInputStream( entry ), sizeBytes ); int origSize = Int32.Parse( new string( Encoding.UTF8.GetChars( sizeBytes ) ), System.Globalization.CultureInfo.InvariantCulture ); worker.ReportProgress( ( tasksComplete++ * 100 ) / tasks, string.Format( "Building {0}", name ) ); sprites.Add( constructor.Invoke( new object[] { new SerializedSprite( name, origSize, filenames, pixels, palettes ) } ) as AbstractSprite ); } } } return new FullSpriteSet( sprites, worker, tasksComplete, tasks ); }
public MapHud(HudManager manager, PluginCore pluginCore, LocationDatabase locationDatabase) : base(DefaultRegion, "Map of Dereth", manager) { mPluginCore = pluginCore; mZipFile = new ZipFile(Util.FullPath(@"Huds\DerethMap.zip")); using (StreamReader mapInfoReader = new StreamReader(mZipFile.GetInputStream(mZipFile.GetEntry("map.txt")))) { // File format has 3 lines: mapSize, tileSize, padding mMapSize = int.Parse(mapInfoReader.ReadLine()); mTileSize = int.Parse(mapInfoReader.ReadLine()); mTilePaddedSize = mTileSize + int.Parse(mapInfoReader.ReadLine()); mMaxTile = (mMapSize - 1) / mTileSize; mPixPerClick = mMapSize / 204.1f; } mActualZoom = mZoomMultiplier; mCoordTickDelta = CalculateCoordTickDelta(Zoom); SetAlphaFading(255, 128); ClientMouseDown += new EventHandler<HudMouseEventArgs>(MapHud_ClientMouseDown); ClientMouseUp += new EventHandler<HudMouseEventArgs>(MapHud_ClientMouseUp); ClientMouseDrag += new EventHandler<HudMouseDragEventArgs>(MapHud_ClientMouseDrag); ClientMouseDoubleClick += new EventHandler<HudMouseEventArgs>(MapHud_ClientMouseDoubleClick); ClientMouseWheel += new EventHandler<HudMouseEventArgs>(MapHud_ClientMouseWheel); ClientMouseMove += new EventHandler<HudMouseEventArgs>(MapHud_ClientMouseMove); ClientMouseLeave += new EventHandler<HudMouseEventArgs>(MapHud_ClientMouseLeave); ResizeEnd += new EventHandler(MapHud_ResizeEnd); ClientVisibleChanged += new EventHandler(MapHud_ClientVisibleChanged); Moving += new EventHandler(MapHud_Moving); Heartbeat += new EventHandler(MapHud_Heartbeat); ResizeDrawMode = HudResizeDrawMode.Repaint; mLocDb = locationDatabase; WindowMessage += new EventHandler<WindowMessageEventArgs>(MapHud_WindowMessage); AlphaChanged += new EventHandler<AlphaChangedEventArgs>(MapHud_AlphaChanged); //MaxSize = new Size(1024, 1024); }
// //Developer: Brian Kenney //Date: 7/29/2012 //Change: remove namespace prefix //Details: //some opf files come with the namespace prefix of odfc, so remvoe the prefix before processing // private static string GetOpfFilePath(ZipFile epubFile) { string tmpXMLStream; ZipEntry zipEntry = epubFile.GetEntry(@"meta-inf/container.xml"); if (zipEntry != null) { XElement containerXml; using (Stream zipStream = epubFile.GetInputStream(zipEntry)) { using (MemoryStream memoryStream = new MemoryStream()) { byte[] buffer = new byte[4096]; // 4K is optimum StreamUtils.Copy(zipStream, memoryStream, buffer); memoryStream.Position = 0; containerXml = XElement.Load(memoryStream); //get stream just in case we have a namespace prefix memoryStream.Position = 0; var sr = new System.IO.StreamReader(memoryStream); tmpXMLStream = sr.ReadToEnd(); } } XNamespace xNamespace = containerXml.Attribute("xmlns") != null ? containerXml.Attribute("xmlns").Value : XNamespace.None; if (xNamespace != XNamespace.None) { return containerXml.Descendants(xNamespace + "rootfile") .FirstOrDefault( p => p.Attribute("media-type") != null && p.Attribute("media-type") .Value.Equals("application/oebps-package+xml", StringComparison.CurrentCultureIgnoreCase)) .Attribute("full-path") .Value; } else { //remove odfc namespace prefix and process XDocument xDocument = XDocument.Parse(tmpXMLStream); xDocument.Root.Add(new XAttribute("xmlns", "urn:oasis:names:tc:opendocument:xmlns:container")); xDocument.Root.Attributes(XNamespace.Xmlns + "odfc").Remove(); containerXml = XElement.Parse(xDocument.ToString()); xNamespace = containerXml.Attribute("xmlns") != null ? containerXml.Attribute("xmlns").Value : XNamespace.None; if (xNamespace != XNamespace.None) { return containerXml.Descendants(xNamespace + "rootfile") .FirstOrDefault( p => p.Attribute("media-type") != null && p.Attribute("media-type") .Value.Equals("application/oebps-package+xml", StringComparison.CurrentCultureIgnoreCase)) .Attribute("full-path") .Value; } } } return null; }
//[system]mapdata.txtファイルを書き出す関数 public void MakeMapDataFile() { //List<string> tmpList = new List<string>(); List <string> notUseList = new List <string>(); try { string str = ""; //ZIP書庫のパス string zipPath = PlayerPrefs.GetString("進行中シナリオ", ""); //書庫に追加するファイルのパス string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "[system]mapdata[system].txt"; //先に[system]mapdata.txtを一時的に書き出しておく。 for (int i = 0; i < mapData.Count; i++) { if (mapData[i].Replace("\n", "").Replace("\r", "") == "") { continue; } str = str + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n"; } str = str + "[END]"; System.IO.File.WriteAllText(file, str); //ZipFileオブジェクトの作成 ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath); zf.Password = Secret.SecretString.zipPass; //先にzip上のmapdataを更新しておく(以降でzip上のmapdataを基に、使っているファイルを判別して不使用ファイルを消す操作をするから) //ZipFileの更新を開始 zf.BeginUpdate(); //ZIP書庫に一時的に書きだしておいたファイルを追加する zf.Add(file, System.IO.Path.GetFileName(file)); //ZipFileの更新をコミット zf.CommitUpdate(); //以下、不使用データの削除処理 ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry("[system]mapdata[system].txt"); tmpList.Clear(); FileSearchLoop(ze, zf); tmpList.Add("[system]mapdata[system].txt"); tmpList.Add("[system]password[system].txt"); tmpList.Add("[system]commandFileNum[system].txt"); tmpList.Add("[system]command1[system]PC版スタート地点[system].txt"); tmpList.Add("[system]PC版スタート地点[system].txt"); foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze3 in zf) { bool useFlag = false; foreach (string tmpStr in tmpList) { if (tmpStr == ze3.Name) { useFlag = true; } } if (useFlag == false) { string tmpStr = ze3.Name; notUseList.Add(tmpStr); } } //ZipFileの更新を開始 zf.BeginUpdate(); foreach (string tmpStr in notUseList) { zf.Delete(tmpStr); } //notUseListのファイルを消す。 //ZipFileの更新をコミット zf.CommitUpdate(); //閉じる zf.Close(); //一時的に書きだした[system]mapdata.txtを消去する。 System.IO.File.Delete(file); } catch { } }
private void AppPropertiesTabControl_SelectedIndexChanged(object sender, EventArgs e) { if (AppPropertiesTabControl.SelectedTab == ExtensionsTabPage && _isPropertiesLoaded) { bool reloadSelected = false; foreach (PropertyManager.AirExtension extension in _extensions) { if (extension.IsValid && string.IsNullOrEmpty(extension.Path)) { var project = PluginCore.PluginBase.CurrentProject as ProjectManager.Projects.Project; foreach (var externalPath in (project.CompilerOptions as MxmlcOptions).ExternalLibraryPaths) { if (Path.GetExtension(externalPath).ToUpperInvariant() == ".ANE") { string absolutePath = project.GetAbsolutePath(externalPath); ZipFile zFile; try { zFile = new ZipFile(absolutePath); } catch (Exception) { continue; } var entry = zFile.GetEntry("META-INF/ANE/extension.xml"); if (entry == null) { continue; } byte[] buffer = UnzipFile(zFile, entry); string extensionId = null; using (var stream = new MemoryStream(buffer)) { using (var reader = XmlReader.Create(stream)) { reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element) continue; if (reader.Name == "id") { extensionId = reader.ReadInnerXml(); break; } } } } if (extensionId == extension.ExtensionId) { reloadSelected = true; extension.Path = absolutePath; } } } } } if (reloadSelected) // In this case, does selecting the first item by default really improve UX in any significant way? LoadSelectedExtension(); } }
/// <summary> /// Removes the file. /// </summary> /// <param name="filename">The filename.</param> /// <remarks>Documented by Dev03, 2009-07-16</remarks> public void RemoveFile(string filename) { ZipFile zipFile = null; try { zipFile = new ZipFile(file.FullName); zipFile.BeginUpdate(); zipFile.Delete(zipFile.GetEntry(filename)); zipFile.CommitUpdate(); } finally { if (zipFile != null) zipFile.Close(); } }