/// <summary> /// Compresses an array of bytes. /// </summary> /// <param name="bytes">The input bytes.</param> /// <returns>Returns the compressed bytes.</returns> /// <exception cref="System.ArgumentNullException">bytes</exception> /// <exception cref="ArgumentNullException">The <paramref name="bytes" /> parameter is null.</exception> public static byte[] Compress(byte[] bytes) { if (bytes == null) throw new ArgumentNullException("bytes"); using (var inputStream = new MemoryStream(bytes)) using (var outputStream = new MemoryStream()) { using (var archive = new ZipArchive(outputStream, ZipArchiveMode.Create, false, null)) using (ZipArchiveEntry entry = archive.CreateEntry(DataEntryName)) using (Stream entryStream = entry.Open()) { inputStream.CopyTo(entryStream); } return outputStream.ToArray(); } }
partial void UnZip(NSObject sender) { // Set the desired output directory to place unzipped files string theUnzippedFolder = Environment.CurrentDirectory + "/unzipped"; // Create a new instance of ZipArchiv ZipArchive zip = new ZipArchive(); // You can subscribe to OnError event so you can handle // any errors situations zip.OnError += (object s, EventArgs e) => { string error = s as String; Console.WriteLine("Error:" + error); }; // Open the zip file you want to unzip zip.UnzipOpenFile(theZipFile); // This will return true if succeeded to unzip bool unzipped = zip.UnzipFileTo(theUnzippedFolder, true); // Dont forget to close the zip file zip.UnzipCloseFile(); if(unzipped) new UIAlertView("Info", "Success: " + theUnzippedFolder, null, "Great", null).Show(); else new UIAlertView("Info", "Something went wrong", null, "Ok", null).Show(); Console.WriteLine(theUnzippedFolder); }
private async static Task<List<StorageFile>> UnZip() { var files = new List(); // open zip var zipFile = await Package.Current.InstalledLocation.GetFileAsync("Data.zip"); using (var zipStream = await zipFile.OpenReadAsync()) { using (var archive = new ZipArchive(zipStream.AsStream())) { // iterate through zipped objects foreach (var archiveEntry in archive.Entries) { using (var outStream = archiveEntry.Open()) { // unzip file to app's LocalFolder var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(archiveEntry.Name); using (var inStream = await file.OpenStreamForWriteAsync()) { await outStream.CopyToAsync(inStream); } files.Add(file); } } } } }
public void TestCompressedZip() { var Zip = new ZipArchive(); Zip.Load("../../../TestInput/UncompressedZip.zip"); var ExpectedString = "ffmpeg -i test.pmf -vcodec copy -an test.h264\nffmpeg -i test.pmf -acodec copy -vn test.ac3p"; var ResultString = Zip["demux.bat"].OpenUncompressedStream().ReadAllContentsAsString(FromStart:false); Assert.AreEqual(ExpectedString, ResultString); }
internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size, DateTime? lastModified) : base(archive, null) { this.Stream = stream; this.path = path; this.size = size; this.lastModified = lastModified; }
public void TestUncompressedZip() { var Zip = new ZipArchive(); Zip.Load("../../../TestInput/UncompressedZip.zip"); foreach (var Entry in Zip) { Console.Error.WriteLine(Entry); } }
public void TestZip2() { var Zip = new ZipArchive(); Zip.Load(ResourceArchive.GetFlash0ZipFileStream()); foreach (var Entry in Zip) { Console.Error.WriteLine(Entry); } }
internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size, DateTime? lastModified, bool closeStream) : base(archive, null) { this.stream = stream; this.path = path; this.size = size; this.LastModifiedTime = lastModified; this.closeStream = closeStream; }
public static async Task ZipWithInvalidFileNames_ParsedBasedOnSourceOS(string zipName, string fileName) { using (Stream stream = await StreamHelpers.CreateTempCopyStream(compat(zipName))) using (ZipArchive archive = new ZipArchive(stream)) { Assert.Equal(1, archive.Entries.Count); ZipArchiveEntry entry = archive.Entries[0]; Assert.Equal(fileName, entry.Name); } }
public static void EmptyEntryTest(ZipArchiveMode mode) { string data1 = "test data written to file."; string data2 = "more test data written to file."; DateTimeOffset lastWrite = new DateTimeOffset(1992, 4, 5, 12, 00, 30, new TimeSpan(-5, 0, 0)); var baseline = new LocalMemoryStream(); using (ZipArchive archive = new ZipArchive(baseline, mode)) { AddEntry(archive, "data1.txt", data1, lastWrite); ZipArchiveEntry e = archive.CreateEntry("empty.txt"); e.LastWriteTime = lastWrite; using (Stream s = e.Open()) { } AddEntry(archive, "data2.txt", data2, lastWrite); } var test = new LocalMemoryStream(); using (ZipArchive archive = new ZipArchive(test, mode)) { AddEntry(archive, "data1.txt", data1, lastWrite); ZipArchiveEntry e = archive.CreateEntry("empty.txt"); e.LastWriteTime = lastWrite; AddEntry(archive, "data2.txt", data2, lastWrite); } //compare Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match"); //second test, this time empty file at end baseline = baseline.Clone(); using (ZipArchive archive = new ZipArchive(baseline, mode)) { AddEntry(archive, "data1.txt", data1, lastWrite); ZipArchiveEntry e = archive.CreateEntry("empty.txt"); e.LastWriteTime = lastWrite; using (Stream s = e.Open()) { } } test = test.Clone(); using (ZipArchive archive = new ZipArchive(test, mode)) { AddEntry(archive, "data1.txt", data1, lastWrite); ZipArchiveEntry e = archive.CreateEntry("empty.txt"); e.LastWriteTime = lastWrite; } //compare Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match after update"); }
public static async Task ReadStreamOps() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read)) { foreach (ZipArchiveEntry e in archive.Entries) { using (Stream s = e.Open()) { Assert.True(s.CanRead, "Can read to read archive"); Assert.False(s.CanWrite, "Can't write to read archive"); Assert.False(s.CanSeek, "Can't seek on archive"); Assert.Equal(ZipTest.LengthOfUnseekableStream(s), e.Length); //"Length is not correct on unseekable stream" } } } }
public static async Task UpdateReadTwice() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(zfile("small.zip")), ZipArchiveMode.Update)) { ZipArchiveEntry entry = archive.Entries[0]; string contents1, contents2; using (StreamReader s = new StreamReader(entry.Open())) { contents1 = s.ReadToEnd(); } using (StreamReader s = new StreamReader(entry.Open())) { contents2 = s.ReadToEnd(); } Assert.Equal(contents1, contents2); } }
private static void WriteFilesRecursiveToZip(ZipArchive archive, IStorage storage, string basePath) { string searchPattern = basePath; string[] fileNames = storage.GetFileNames(searchPattern); foreach (string fileName in fileNames) { Stream fileStream = storage.OpenFile(basePath + "/" + fileName, StorageFileMode.Open, StorageFileAccess.Read); archive.AddEntry(fileName, fileStream); } string[] directrryNames = storage.GetDirectoryNames(searchPattern); foreach (string directoryName in directrryNames) { WriteFilesRecursiveToZip(archive, storage, basePath + "/" + directoryName); } }
private void ButtonOpenClick(object sender, RoutedEventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Zip File | *.zip"; bool? dialogResult = dialog.ShowDialog(); if (dialogResult == true) { #if WPF Stream stream = dialog.OpenFile(); #else Stream stream = dialog.File.OpenRead(); #endif using (ZipArchive zipArchive = new ZipArchive(stream)) { OpenedFileList.ItemsSource = zipArchive.Entries; } } }
void CreateZip() { Console.WriteLine("creating zip file"); // Needed contents at ZipPath: // Files\Application\ --> All contents requied for Programm Files (x86)\Sharpkit\ // Files\NET\ --> the content of FrameworkDir\SharpKit // Files\NET_Unix\ --> only the modified files for unix. At this time, it will contain only the file SharpKit.Build.targets. // Files\Templates\ --> contains 'SharpKit Web Application.zip' and 'SharpKit 5 Web Application.zip' // Just copy the needed above files to @SourceFilesDir() and run this code. // @SourceFilesDir must be the parent directory of Files\ using (var zip = new ZipArchive(ZipPath) { AddFileCallback = t => Console.WriteLine(t) }) { zip.BeginUpdate(); zip.AddDirectory(SourceFilesDir); zip.EndUpdate(); } }
/// <summary> /// Decompresses an array of bytes. /// </summary> /// <param name="bytes">The compressed bytes.</param> /// <returns>Returns the uncompressed bytes.</returns> /// <exception cref="System.ArgumentNullException">bytes</exception> /// <exception cref="ArgumentNullException">The <paramref name="bytes" /> parameter is null.</exception> public static byte[] Uncompress(byte[] bytes) { if (bytes == null) throw new ArgumentNullException("bytes"); using (var inputStream = new MemoryStream(bytes)) { using (var zipPackage = new ZipArchive(inputStream, ZipArchiveMode.Read, true, null)) { using (var outputStream = new MemoryStream()) { var entry = zipPackage.Entries.FirstOrDefault(e => e.Name == DataEntryName); if (entry != null) entry.Open().CopyTo(outputStream); return outputStream.ToArray(); } } } }
private void ButtonSaveClick(object sender, RoutedEventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "Zip File | *.zip"; bool? dialogResult = dialog.ShowDialog(); if (dialogResult == true) { using (ZipArchive zipArchive = new ZipArchive(dialog.OpenFile(), ZipArchiveMode.Create, false, null)) { IEnumerable<DataItem> selectedFiles = items.Where(CheckIsFileSelected); foreach (DataItem file in selectedFiles) { MemoryStream stream = CreateNewFile(file); using (ZipArchiveEntry archiveEntry = zipArchive.CreateEntry(file.FileName)) { Stream entryStream = archiveEntry.Open(); stream.CopyTo(entryStream); } } } } }
public static void CreateModeInvalidOperations() { MemoryStream ms = new MemoryStream(); ZipArchive z = new ZipArchive(ms, ZipArchiveMode.Create); Assert.Throws<NotSupportedException>(() => { var x = z.Entries; }); //"Entries not applicable on Create" Assert.Throws<NotSupportedException>(() => z.GetEntry("dirka")); //"GetEntry not applicable on Create" ZipArchiveEntry e = z.CreateEntry("hey"); Assert.Throws<NotSupportedException>(() => e.Delete()); //"Can't delete new entry" Stream s = e.Open(); Assert.Throws<NotSupportedException>(() => s.ReadByte()); //"Can't read on new entry" Assert.Throws<NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"Can't seek on new entry" Assert.Throws<NotSupportedException>(() => s.Position = 0); //"Can't set position on new entry" Assert.Throws<NotSupportedException>(() => { var x = s.Length; }); //"Can't get length on new entry" Assert.Throws<IOException>(() => e.LastWriteTime = new DateTimeOffset()); //"Can't get LastWriteTime on new entry" Assert.Throws<InvalidOperationException>(() => { var x = e.Length; }); //"Can't get length on new entry" Assert.Throws<InvalidOperationException>(() => { var x = e.CompressedLength; }); //"can't get CompressedLength on new entry" Assert.Throws<IOException>(() => z.CreateEntry("bad")); s.Dispose(); Assert.Throws<ObjectDisposedException>(() => s.WriteByte(25)); //"Can't write to disposed entry" Assert.Throws<IOException>(() => e.Open()); Assert.Throws<IOException>(() => e.LastWriteTime = new DateTimeOffset()); Assert.Throws<InvalidOperationException>(() => { var x = e.Length; }); Assert.Throws<InvalidOperationException>(() => { var x = e.CompressedLength; }); ZipArchiveEntry e1 = z.CreateEntry("e1"); ZipArchiveEntry e2 = z.CreateEntry("e2"); Assert.Throws<IOException>(() => e1.Open()); //"Can't open previous entry after new entry created" z.Dispose(); Assert.Throws<ObjectDisposedException>(() => z.CreateEntry("dirka")); //"Can't create after dispose" }
public static void Extract(Stream zipStream, string targetDirectory) { var zipArchive = new ZipArchive(); zipArchive.ReadFrom(zipStream); foreach (var entry in zipArchive.Entries) { if (entry is ZipFileEntry) { var fileEntry = entry as ZipFileEntry; string absoluteFilePath = Path.Combine(targetDirectory, fileEntry.FileName); string directoryName = Path.GetDirectoryName(absoluteFilePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } if (File.Exists(absoluteFilePath)) { File.Delete(absoluteFilePath); } var fileStream = new FileStream(absoluteFilePath, FileMode.CreateNew); if (fileEntry.Data != null && fileEntry.Data.Length != 0) { WriteStream(fileEntry.Data, fileStream); } fileStream.Close(); } else if (entry is ZipDirectoryEntry) { var directoryEntry = entry as ZipDirectoryEntry; string directoryName = Path.Combine(targetDirectory, directoryEntry.DirectoryName); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } } } }
/// <summary> /// Create a new archive archiveFile with no data (empty). It is expected that only ZipArchive methods will /// use this routine. /// </summary> internal ZipArchiveFile(ZipArchive archive, string archiveName) { this.archive = archive; name = archiveName; if (name != null) archive.entries[name] = this; lastWriteTime = DateTime.Now; }
public ItemsTabPage() { if (Items == null) { using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream("QTRHacker.NewDimension.Res.Game.WikiRes.zip")) { ZipArchive z = new ZipArchive(s); using (var u = new StreamReader(z.GetEntry("ItemInfo.json").Open())) Items = JArray.Parse(u.ReadToEnd()); using (var u = new StreamReader(z.GetEntry("ItemName_cn.json").Open())) Items_cn = JArray.Parse(u.ReadToEnd()); using (var u = new StreamReader(z.GetEntry("RecipeInfo.json").Open())) Recipes = JArray.Parse(u.ReadToEnd()); } } this.BackColor = Color.LightGray; this.BorderStyle = BorderStyle.None; ItemListView = new ListView(); ItemListView.Bounds = new Rectangle(5, 5, 450, 440); ItemListView.FullRowSelect = true; ItemListView.MultiSelect = false; ItemListView.HideSelection = false; ItemListView.View = View.Details; ItemListView.Columns.Add(MainForm.CurrentLanguage["Index"], 50); ItemListView.Columns.Add(MainForm.CurrentLanguage["Rare"], 50); ItemListView.Columns.Add(MainForm.CurrentLanguage["EnglishName"], 125); ItemListView.Columns.Add(MainForm.CurrentLanguage["ChineseName"], 125); ItemListView.Columns.Add(MainForm.CurrentLanguage["Type"], 70); ItemListView.MouseDoubleClick += (s, e) => { int id = Convert.ToInt32(ItemListView.SelectedItems[0].Text.ToString()); var player = HackContext.GameContext.MyPlayer; int num = QTRHacker.Functions.GameObjects.Item.NewItem(HackContext.GameContext, player.X, player.Y, 0, 0, id, Items[id]["maxStack"].ToObject <int>(), false, 0, true); QTRHacker.Functions.GameObjects.NetMessage.SendData(HackContext.GameContext, 21, -1, -1, 0, num, 0, 0, 0, 0, 0, 0); }; ItemListView.SelectedIndexChanged += ItemListView_SelectedIndexChanged; ItemInfoPage = new TabPage(MainForm.CurrentLanguage["ItemInfo"]); { ItemIconInfoView = new InfoView(new PictureBox() { SizeMode = PictureBoxSizeMode.CenterImage }, InfoView.TipDock.Top); ItemIconInfoView.Text = MainForm.CurrentLanguage["Icon"]; ItemIconInfoView.Bounds = new Rectangle(5, 5, 80, 80); ItemIconInfoView.Tip.BackColor = ItemsColor; ItemNameInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Right }, InfoView.TipDock.Left, false); ItemNameInfoView.Text = MainForm.CurrentLanguage["Name"]; ItemNameInfoView.Tip.BackColor = ItemsColor; ItemNameInfoView.Bounds = new Rectangle(0, 0, 170, 20); ItemTypeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Right }, InfoView.TipDock.Left, false); ItemTypeInfoView.Text = MainForm.CurrentLanguage["Type"]; ItemTypeInfoView.Tip.BackColor = ItemsColor; ItemTypeInfoView.Bounds = new Rectangle(0, 20, 170, 20); ItemRareInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Right }, InfoView.TipDock.Left, false); ItemRareInfoView.Text = MainForm.CurrentLanguage["Rare"]; ItemRareInfoView.Tip.BackColor = ItemsColor; ItemRareInfoView.Bounds = new Rectangle(0, 40, 170, 20); InfoView ItemDetailInfoView = new InfoView(new Panel() { BorderStyle = BorderStyle.None }, InfoView.TipDock.Top); Panel ItemDetailInfoViewContent = (ItemDetailInfoView.View as Panel); ItemDetailInfoViewContent.Controls.Add(ItemNameInfoView); ItemDetailInfoViewContent.Controls.Add(ItemTypeInfoView); ItemDetailInfoViewContent.Controls.Add(ItemRareInfoView); ItemDetailInfoView.Text = MainForm.CurrentLanguage["Details"]; ItemDetailInfoView.Tip.BackColor = ItemsColor; ItemDetailInfoView.Bounds = new Rectangle(90, 5, 170, 80); ItemDescriptionInfoView = new InfoView(new TextBox() { Multiline = true }, InfoView.TipDock.Left); ItemDescriptionInfoView.Text = MainForm.CurrentLanguage["Description"]; ItemDescriptionInfoView.Tip.BackColor = ItemsColor; ItemDescriptionInfoView.Bounds = new Rectangle(5, 90, 255, 80); ListBox requireItems = new ListBox() { BorderStyle = BorderStyle.None }; requireItems.MouseDoubleClick += RequireItems_MouseDoubleClick; ItemRecipeFromInfoView = new InfoView(requireItems, InfoView.TipDock.Top); ItemRecipeFromInfoView.Text = MainForm.CurrentLanguage["Recipe"] + "(From)"; ItemRecipeFromInfoView.Tip.BackColor = ItemsColor; ItemRecipeFromInfoView.Bounds = new Rectangle(5, 175, 255, 100); ListBox recipeToItems = new ListBox() { BorderStyle = BorderStyle.None }; recipeToItems.MouseDoubleClick += RecipeToItems_MouseDoubleClick; ItemRecipeToInfoView = new InfoView(recipeToItems, InfoView.TipDock.Top); ItemRecipeToInfoView.Text = MainForm.CurrentLanguage["Recipe"] + "(To)"; ItemRecipeToInfoView.Tip.BackColor = ItemsColor; ItemRecipeToInfoView.Bounds = new Rectangle(5, 280, 255, 100); ItemValueInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left); ItemValueInfoView.Text = MainForm.CurrentLanguage["Rare"]; ItemValueInfoView.Tip.BackColor = ItemsColor; ItemValueInfoView.Bounds = new Rectangle(5, 385, 255, 20); ItemInfoPage.Controls.Add(ItemIconInfoView); ItemInfoPage.Controls.Add(ItemDetailInfoView); ItemInfoPage.Controls.Add(ItemDescriptionInfoView); ItemInfoPage.Controls.Add(ItemRecipeFromInfoView); ItemInfoPage.Controls.Add(ItemRecipeToInfoView); ItemInfoPage.Controls.Add(ItemValueInfoView); } AccInfoPage = new TabPage(MainForm.CurrentLanguage["ArmorInfo"]); { ItemIcon2InfoView = new InfoView(new PictureBox() { SizeMode = PictureBoxSizeMode.CenterImage }, InfoView.TipDock.Top); ItemIcon2InfoView.Text = MainForm.CurrentLanguage["Icon"]; ItemIcon2InfoView.Bounds = new Rectangle(5, 5, 80, 80); ItemIcon2InfoView.Tip.BackColor = ItemsColor; ItemPickaxeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false); ItemPickaxeInfoView.Text = MainForm.CurrentLanguage["Pick"]; ItemPickaxeInfoView.Tip.BackColor = ItemsColor; ItemPickaxeInfoView.Bounds = new Rectangle(0, 0, 170, 20); ItemAxeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false); ItemAxeInfoView.Text = MainForm.CurrentLanguage["Axe"]; ItemAxeInfoView.Tip.BackColor = ItemsColor; ItemAxeInfoView.Bounds = new Rectangle(0, 20, 170, 20); ItemHammerInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false); ItemHammerInfoView.Text = MainForm.CurrentLanguage["Hammer"]; ItemHammerInfoView.Tip.BackColor = ItemsColor; ItemHammerInfoView.Bounds = new Rectangle(0, 40, 170, 20); InfoView ItemDetailInfoView = new InfoView(new Panel() { BorderStyle = BorderStyle.None }, InfoView.TipDock.Top); Panel ItemDetailInfoViewContent = (ItemDetailInfoView.View as Panel); ItemDetailInfoViewContent.Controls.Add(ItemPickaxeInfoView); ItemDetailInfoViewContent.Controls.Add(ItemAxeInfoView); ItemDetailInfoViewContent.Controls.Add(ItemHammerInfoView); ItemDetailInfoView.Text = MainForm.CurrentLanguage["Details"]; ItemDetailInfoView.Tip.BackColor = ItemsColor; ItemDetailInfoView.Bounds = new Rectangle(90, 5, 170, 80); ItemDamageInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemDamageInfoView.Text = MainForm.CurrentLanguage["Damage"]; ItemDamageInfoView.Tip.BackColor = ItemsColor; ItemDamageInfoView.Bounds = new Rectangle(0, 0, 127, 20); ItemDefenseInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemDefenseInfoView.Text = MainForm.CurrentLanguage["Defense"]; ItemDefenseInfoView.Tip.BackColor = ItemsColor; ItemDefenseInfoView.Bounds = new Rectangle(128, 0, 127, 20); ItemCritInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemCritInfoView.Text = MainForm.CurrentLanguage["Crit"]; ItemCritInfoView.Tip.BackColor = ItemsColor; ItemCritInfoView.Bounds = new Rectangle(0, 20, 127, 20); ItemKnockbackInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemKnockbackInfoView.Text = MainForm.CurrentLanguage["KnockBack"]; ItemKnockbackInfoView.Tip.BackColor = ItemsColor; ItemKnockbackInfoView.Bounds = new Rectangle(128, 20, 127, 20); ItemShootInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemShootInfoView.Text = MainForm.CurrentLanguage["Shoot"]; ItemShootInfoView.Tip.BackColor = ItemsColor; ItemShootInfoView.Bounds = new Rectangle(0, 40, 127, 20); ItemShootSpeedInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemShootSpeedInfoView.Text = MainForm.CurrentLanguage["ShootSpeed"]; ItemShootSpeedInfoView.Tip.BackColor = ItemsColor; ItemShootSpeedInfoView.Bounds = new Rectangle(128, 40, 127, 20); ItemUseTimeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemUseTimeInfoView.Text = MainForm.CurrentLanguage["UseTime"]; ItemUseTimeInfoView.Tip.BackColor = ItemsColor; ItemUseTimeInfoView.Bounds = new Rectangle(0, 60, 127, 20); ItemUseAnimationInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemUseAnimationInfoView.Text = MainForm.CurrentLanguage["UseAnimation"]; ItemUseAnimationInfoView.Tip.BackColor = ItemsColor; ItemUseAnimationInfoView.Bounds = new Rectangle(128, 60, 127, 20); ItemHealLifeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemHealLifeInfoView.Text = MainForm.CurrentLanguage["HealLife"]; ItemHealLifeInfoView.Tip.BackColor = ItemsColor; ItemHealLifeInfoView.Bounds = new Rectangle(0, 80, 127, 20); ItemHealManaInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemHealManaInfoView.Text = MainForm.CurrentLanguage["HealMana"]; ItemHealManaInfoView.Tip.BackColor = ItemsColor; ItemHealManaInfoView.Bounds = new Rectangle(128, 80, 127, 20); ItemCreateTileInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemCreateTileInfoView.Text = MainForm.CurrentLanguage["CreateTile"]; ItemCreateTileInfoView.Tip.BackColor = ItemsColor; ItemCreateTileInfoView.Bounds = new Rectangle(0, 100, 127, 20); ItemPlaceStyleInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemPlaceStyleInfoView.Text = MainForm.CurrentLanguage["PlaceStyle"]; ItemPlaceStyleInfoView.Tip.BackColor = ItemsColor; ItemPlaceStyleInfoView.Bounds = new Rectangle(128, 100, 127, 20); ItemCreateWallInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemCreateWallInfoView.Text = MainForm.CurrentLanguage["CreateWall"]; ItemCreateWallInfoView.Tip.BackColor = ItemsColor; ItemCreateWallInfoView.Bounds = new Rectangle(0, 120, 127, 20); ItemTileBoostInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemTileBoostInfoView.Text = MainForm.CurrentLanguage["TileBoost"]; ItemTileBoostInfoView.Tip.BackColor = ItemsColor; ItemTileBoostInfoView.Bounds = new Rectangle(128, 120, 127, 20); ItemBuffTypeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemBuffTypeInfoView.Text = MainForm.CurrentLanguage["Buff"]; ItemBuffTypeInfoView.Tip.BackColor = ItemsColor; ItemBuffTypeInfoView.Bounds = new Rectangle(0, 140, 127, 20); ItemBuffTimeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemBuffTimeInfoView.Text = MainForm.CurrentLanguage["BuffTime"]; ItemBuffTimeInfoView.Tip.BackColor = ItemsColor; ItemBuffTimeInfoView.Bounds = new Rectangle(128, 140, 127, 20); ItemManaConsumeInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemManaConsumeInfoView.Text = MainForm.CurrentLanguage["ManaConsume"]; ItemManaConsumeInfoView.Tip.BackColor = ItemsColor; ItemManaConsumeInfoView.Bounds = new Rectangle(0, 160, 127, 20); ItemBaitInfoView = new InfoView(new TextBox() { TextAlign = HorizontalAlignment.Center }, InfoView.TipDock.Left, false, 60); ItemBaitInfoView.Text = MainForm.CurrentLanguage["Bait"]; ItemBaitInfoView.Tip.BackColor = ItemsColor; ItemBaitInfoView.Bounds = new Rectangle(128, 160, 127, 20); InfoView ItemPropertiesInfoView = new InfoView(new Panel() { BorderStyle = BorderStyle.None }, InfoView.TipDock.Top); Panel ItemPropertiesInfoViewContent = (ItemPropertiesInfoView.View as Panel); ItemPropertiesInfoViewContent.Controls.Add(ItemDamageInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemDefenseInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemCritInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemKnockbackInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemShootInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemShootSpeedInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemUseTimeInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemUseAnimationInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemHealLifeInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemHealManaInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemCreateTileInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemPlaceStyleInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemCreateWallInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemTileBoostInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemBuffTypeInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemBuffTimeInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemManaConsumeInfoView); ItemPropertiesInfoViewContent.Controls.Add(ItemBaitInfoView); ItemPropertiesInfoView.Text = MainForm.CurrentLanguage["Properties"]; ItemPropertiesInfoView.Tip.BackColor = ItemsColor; ItemPropertiesInfoView.Bounds = new Rectangle(5, 105, 255, 10 * 20); ItemDescription2InfoView = new InfoView(new TextBox() { Multiline = true }, InfoView.TipDock.Left); ItemDescription2InfoView.Text = MainForm.CurrentLanguage["Description"]; ItemDescription2InfoView.Tip.BackColor = ItemsColor; ItemDescription2InfoView.Bounds = new Rectangle(5, 320, 255, 80); AccInfoPage.Controls.Add(ItemIcon2InfoView); AccInfoPage.Controls.Add(ItemDetailInfoView); AccInfoPage.Controls.Add(ItemPropertiesInfoView); AccInfoPage.Controls.Add(ItemDescription2InfoView); } SearcherPage = new TabPage(MainForm.CurrentLanguage["Search"]); { GroupBox filterGroupBox = new GroupBox(); filterGroupBox.Text = MainForm.CurrentLanguage["Filter"]; filterGroupBox.Bounds = new Rectangle(5, 10, 255, 105); BlockCheckBox = new CheckBox(); BlockCheckBox.Text = MainForm.CurrentLanguage["Blocks"]; BlockCheckBox.Checked = true; BlockCheckBox.Bounds = new Rectangle(5, 20, 50, 20); BlockCheckBox.CheckedChanged += Filter_CheckedChanged; WallCheckBox = new CheckBox(); WallCheckBox.Text = MainForm.CurrentLanguage["Walls"]; WallCheckBox.Checked = true; WallCheckBox.Bounds = new Rectangle(70, 20, 50, 20); WallCheckBox.CheckedChanged += Filter_CheckedChanged; HeadCheckBox = new CheckBox(); HeadCheckBox.Text = MainForm.CurrentLanguage["Head"]; HeadCheckBox.Checked = true; HeadCheckBox.Bounds = new Rectangle(5, 40, 50, 20); HeadCheckBox.CheckedChanged += Filter_CheckedChanged; BodyCheckBox = new CheckBox(); BodyCheckBox.Text = MainForm.CurrentLanguage["Body"]; BodyCheckBox.Checked = true; BodyCheckBox.Bounds = new Rectangle(70, 40, 50, 20); BodyCheckBox.CheckedChanged += Filter_CheckedChanged; LegCheckBox = new CheckBox(); LegCheckBox.Text = MainForm.CurrentLanguage["Leg"]; LegCheckBox.Checked = true; LegCheckBox.Bounds = new Rectangle(135, 40, 50, 20); LegCheckBox.CheckedChanged += Filter_CheckedChanged; AccessoryCheckBox = new CheckBox(); AccessoryCheckBox.Text = MainForm.CurrentLanguage["Accessory"]; AccessoryCheckBox.Checked = true; AccessoryCheckBox.Bounds = new Rectangle(200, 40, 50, 20); AccessoryCheckBox.CheckedChanged += Filter_CheckedChanged; MeleeCheckBox = new CheckBox(); MeleeCheckBox.Text = MainForm.CurrentLanguage["Melee"]; MeleeCheckBox.Checked = true; MeleeCheckBox.Bounds = new Rectangle(5, 60, 50, 20); MeleeCheckBox.CheckedChanged += Filter_CheckedChanged; RangedCheckBox = new CheckBox(); RangedCheckBox.Text = MainForm.CurrentLanguage["Ranged"]; RangedCheckBox.Checked = true; RangedCheckBox.Bounds = new Rectangle(70, 60, 50, 20); RangedCheckBox.CheckedChanged += Filter_CheckedChanged; MagicCheckBox = new CheckBox(); MagicCheckBox.Text = MainForm.CurrentLanguage["Magic"]; MagicCheckBox.Checked = true; MagicCheckBox.Bounds = new Rectangle(135, 60, 50, 20); MagicCheckBox.CheckedChanged += Filter_CheckedChanged; SummonCheckBox = new CheckBox(); SummonCheckBox.Text = MainForm.CurrentLanguage["Summon"]; SummonCheckBox.Checked = true; SummonCheckBox.Bounds = new Rectangle(200, 60, 50, 20); SummonCheckBox.CheckedChanged += Filter_CheckedChanged; BuffCheckBox = new CheckBox(); BuffCheckBox.Text = MainForm.CurrentLanguage["Buff"]; BuffCheckBox.Checked = true; BuffCheckBox.Bounds = new Rectangle(5, 80, 50, 20); BuffCheckBox.CheckedChanged += Filter_CheckedChanged; ConsumableCheckBox = new CheckBox(); ConsumableCheckBox.Text = MainForm.CurrentLanguage["Consumable"]; ConsumableCheckBox.Checked = true; ConsumableCheckBox.Bounds = new Rectangle(70, 80, 50, 20); ConsumableCheckBox.CheckedChanged += Filter_CheckedChanged; OthersCheckBox = new CheckBox(); OthersCheckBox.Text = MainForm.CurrentLanguage["Others"]; OthersCheckBox.Checked = true; OthersCheckBox.Bounds = new Rectangle(135, 80, 50, 20); OthersCheckBox.CheckedChanged += Filter_CheckedChanged; filterGroupBox.Controls.Add(BlockCheckBox); filterGroupBox.Controls.Add(WallCheckBox); filterGroupBox.Controls.Add(HeadCheckBox); filterGroupBox.Controls.Add(BodyCheckBox); filterGroupBox.Controls.Add(LegCheckBox); filterGroupBox.Controls.Add(AccessoryCheckBox); filterGroupBox.Controls.Add(MeleeCheckBox); filterGroupBox.Controls.Add(RangedCheckBox); filterGroupBox.Controls.Add(MagicCheckBox); filterGroupBox.Controls.Add(SummonCheckBox); filterGroupBox.Controls.Add(BuffCheckBox); filterGroupBox.Controls.Add(ConsumableCheckBox); filterGroupBox.Controls.Add(OthersCheckBox); Label tipSearch = new Label(); tipSearch.Text = MainForm.CurrentLanguage["KeyWord"] + ":"; tipSearch.Bounds = new Rectangle(15, 133, 50, 20); KeyWordTextBox = new TextBox(); KeyWordTextBox.Bounds = new Rectangle(65, 130, 175, 20); KeyWordTextBox.KeyDown += (s, e) => { if (e.KeyCode == Keys.Enter) { e.Handled = true; KeyWord = KeyWordTextBox.Text; RefreshItems(); } }; Button searchButton = new Button(); searchButton.Text = MainForm.CurrentLanguage["Search"]; searchButton.Bounds = new Rectangle(70, 160, 60, 20); searchButton.Click += (s, e) => { KeyWord = KeyWordTextBox.Text; RefreshItems(); }; Button resetButton = new Button(); resetButton.Text = MainForm.CurrentLanguage["Reset"]; resetButton.Bounds = new Rectangle(130, 160, 60, 20); resetButton.Click += (s, e) => { KeyWord = ""; KeyWordTextBox.Text = ""; RefreshItems(); }; SearcherPage.Controls.Add(filterGroupBox); SearcherPage.Controls.Add(tipSearch); SearcherPage.Controls.Add(KeyWordTextBox); SearcherPage.Controls.Add(searchButton); SearcherPage.Controls.Add(resetButton); } InfoTabs = new MTabControl(); InfoTabs.Bounds = new Rectangle(460, 5, 270, 440); InfoTabs.Controls.Add(ItemInfoPage); InfoTabs.Controls.Add(AccInfoPage); InfoTabs.Controls.Add(SearcherPage); Controls.Add(ItemListView); Controls.Add(InfoTabs); }
public static ZipArchive ReadZipFile(string filename, bool strictConsistencyChecks = false) { return(ZipArchive.Open(filename, FileMode.Open, strictConsistencyChecks: strictConsistencyChecks)); }
private void mnuInstallHdPack_Click(object sender, EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.SetFilter(ResourceHelper.GetMessage("FilterZipFiles")); if (ofd.ShowDialog(this) == DialogResult.OK) { try { using (FileStream stream = File.Open(ofd.FileName, FileMode.Open)) { ZipArchive zip = new ZipArchive(stream); //Find the hires.txt file ZipArchiveEntry hiresEntry = null; foreach (ZipArchiveEntry entry in zip.Entries) { if (entry.Name == "hires.txt") { hiresEntry = entry; break; } } if (hiresEntry != null) { using (Stream entryStream = hiresEntry.Open()) { using (StreamReader reader = new StreamReader(entryStream)) { string hiresData = reader.ReadToEnd(); RomInfo romInfo = InteropEmu.GetRomInfo(); //If there's a "supportedRom" tag, check if it matches the current ROM Regex supportedRomRegex = new Regex("<supportedRom>([^\\n]*)"); Match match = supportedRomRegex.Match(hiresData); if (match.Success) { if (!match.Groups[1].Value.ToUpper().Contains(InteropEmu.GetRomInfo().Sha1.ToUpper())) { MesenMsgBox.Show("InstallHdPackWrongRom", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } //Extract HD pack try { string targetFolder = Path.Combine(ConfigManager.HdPackFolder, romInfo.GetRomName()); if (Directory.Exists(targetFolder)) { //Warn if the folder already exists if (MesenMsgBox.Show("InstallHdPackConfirmOverwrite", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, targetFolder) != DialogResult.OK) { return; } } else { Directory.CreateDirectory(targetFolder); } string hiresFileFolder = hiresEntry.FullName.Substring(0, hiresEntry.FullName.Length - "hires.txt".Length); foreach (ZipArchiveEntry entry in zip.Entries) { //Extract only the files in the same subfolder as the hires.txt file (and only if they have a name & size > 0) if (!string.IsNullOrWhiteSpace(entry.Name) && entry.Length > 0 && entry.FullName.StartsWith(hiresFileFolder)) { entry.ExtractToFile(Path.Combine(targetFolder, entry.Name), true); } } } catch (Exception ex) { MesenMsgBox.Show("InstallHdPackError", MessageBoxButtons.OK, MessageBoxIcon.Error, ex.ToString()); return; } } //Turn on HD Pack support automatically after installation succeeds ConfigManager.Config.VideoInfo.UseHdPacks = true; ConfigManager.ApplyChanges(); ConfigManager.Config.ApplyConfig(); if (MesenMsgBox.Show("InstallHdPackConfirmReset", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { //Power cycle game if the user agrees InteropEmu.PowerCycle(); } } } else { MesenMsgBox.Show("InstallHdPackInvalidPack", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch { //Invalid file (file missing, not a zip file, etc.) MesenMsgBox.Show("InstallHdPackInvalidZipFile", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
protected internal override void OnStart(string[] args) { TR.Enter(); bool useRPC = false, nopeers = false, useLog = false; for (int i = 0; i < args.Length; i++) { switch (args[i]) { case "/rpc": case "--rpc": case "-r": useRPC = true; break; case "--nopeers": nopeers = true; break; case "-l": case "--log": useLog = true; break; } } Blockchain.RegisterBlockchain(new LevelDBBlockchain(Path.GetFullPath(Settings.Default.Paths.Chain))); if (!nopeers && File.Exists(PeerStatePath)) { using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { LocalNode.LoadState(fs); } } LocalNode = new LocalNode(); if (useLog) { LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted; } Task.Run(() => { TR.Log("Task.Run() >"); const string path_acc = "chain.acc"; if (File.Exists(path_acc)) { using (FileStream fs = new FileStream(path_acc, FileMode.Open, FileAccess.Read, FileShare.None)) { ImportBlocks(fs); } } const string path_acc_zip = path_acc + ".zip"; if (File.Exists(path_acc_zip)) { using (FileStream fs = new FileStream(path_acc_zip, FileMode.Open, FileAccess.Read, FileShare.None)) using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read)) using (Stream zs = zip.GetEntry(path_acc).Open()) { ImportBlocks(zs); } } var paths = Directory.EnumerateFiles(".", "chain.*.acc", SearchOption.TopDirectoryOnly).Concat(Directory.EnumerateFiles(".", "chain.*.acc.zip", SearchOption.TopDirectoryOnly)).Select(p => new { FileName = Path.GetFileName(p), Start = uint.Parse(Regex.Match(p, @"\d+").Value), IsCompressed = p.EndsWith(".zip") }).OrderBy(p => p.Start); foreach (var path in paths) { if (path.Start > Blockchain.Default.Height + 1) { break; } if (path.IsCompressed) { using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None)) using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read)) using (Stream zs = zip.GetEntry(Path.GetFileNameWithoutExtension(path.FileName)).Open()) { ImportBlocks(zs, true); } } else { using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None)) { ImportBlocks(fs, true); } } } LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort); if (Settings.Default.UnlockWallet.IsActive) { try { Program.Wallet = OpenWallet(Settings.Default.UnlockWallet.Path, Settings.Default.UnlockWallet.Password); } catch (CryptographicException) { Console.WriteLine($"failed to open file \"{Settings.Default.UnlockWallet.Path}\""); } if (Settings.Default.UnlockWallet.StartConsensus && Program.Wallet != null) { OnStartConsensusCommand(null); } } if (useRPC) { rpc = new RpcServerWithWallet(LocalNode); rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword); } TR.Log("Task.Run() <"); }); TR.Exit(); }
/// <summary> /// Nupkg package reader /// </summary> /// <param name="zipArchive">ZipArchive containing the nupkg data.</param> public PackageArchiveReader(ZipArchive zipArchive) : this(zipArchive, DefaultFrameworkNameProvider.Instance, DefaultCompatibilityProvider.Instance) { }
/// <summary> /// Reads the application info. /// </summary> /// <param name="appArchiveFilePath">Path to the file of the application bundle.</param> /// <returns>The <see cref="XapInfo"/> containing the information about the application.</returns> public static XapInfo ReadApplicationInfo(string appArchiveFilePath) { XapInfo appInfo = new XapInfo(appArchiveFilePath); try { // Do not use "using" for the FileStream. The ZipArchive will close/dispose the stream unless // we specify otherwise. FileStream appArchiveFileStream = new FileStream(appArchiveFilePath, FileMode.Open, FileAccess.Read); using (ZipArchive zipArchive = new ZipArchive(appArchiveFileStream, ZipArchiveMode.Read)) { ZipArchiveEntry appManifestEntry = zipArchive.GetEntry("WMAppManifest.xml"); using (Stream appManifestFileStream = appManifestEntry.Open()) { XPathDocument manifestDocument = new XPathDocument(appManifestFileStream); XPathNavigator manifestNavigator = manifestDocument.CreateNavigator(); XPathNavigator appNodeNavigator = manifestNavigator.SelectSingleNode("//App"); appInfo.ApplicationId = new Guid?(new Guid(appNodeNavigator.GetAttribute("ProductID", string.Empty))); string attribute = appNodeNavigator.GetAttribute("RuntimeType", string.Empty); if (attribute.Equals("Modern Native", StringComparison.OrdinalIgnoreCase)) { appInfo.IsNative = true; } manifestNavigator.MoveToFirstChild(); appInfo.ManifestVersion = new Version(manifestNavigator.GetAttribute("AppPlatformVersion", string.Empty)); } } } catch (Exception ex) { throw new ConsoleDriverException("Unexpected error reading application information.", ex); } return appInfo; }
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { var backgroundWorker = sender as BackgroundWorker; var packListCount = packList.Count; float i = 0; List <string> modFileLines = new List <string>(File.ReadAllLines(Properties.Settings.Default.Modlist_Directory)); try { using (ZipArchive archive = ZipFile.OpenRead(packPath)) { backgroundWorker.ReportProgress(0, "Opening TTMP Data File...\n"); foreach (var entry in archive.Entries) { if (entry.FullName.EndsWith(".mpd")) { var stream = entry.Open(); var remainingPack = packListCount; var currentPack = 0; var prevPack = 0; long newOffset = 0; long offsetSum = 0; List <ModPackItems> pack; long cursor = 0; while (currentPack != packListCount) { prevPack = currentPack; if (remainingPack > 100) { pack = packList.GetRange(currentPack, 100); currentPack += 100; remainingPack -= 100; } else { pack = packList.GetRange(currentPack, remainingPack); currentPack += remainingPack; } backgroundWorker.ReportProgress((int)((i / packListCount) * 100), $"\nReading Entries ({prevPack} - {currentPack}/{packListCount})\n\n"); long totalSize = 0; var modPackBytes = new List <byte>(); foreach (var p in pack) { if (p.mEntry.ModOffset < cursor) { backgroundWorker.ReportProgress((int)((i / packListCount) * 100), $"There was an warning in importing. \nImproper Mod Offset in ModPack for {p.mEntry.Name}. \nUnable to import {p.mEntry.Name}."); continue; } totalSize += p.mEntry.ModSize; var buf = new byte[p.mEntry.ModSize]; while (p.mEntry.ModOffset > cursor) { cursor++; stream.ReadByte(); //seek forward for next offset } stream.Read(buf, 0, buf.Length); cursor += buf.Length; modPackBytes.AddRange(buf); } var uncompBytes = modPackBytes.ToArray(); offsetSum += newOffset; newOffset = totalSize; using (var ms = new MemoryStream(uncompBytes)) { //backgroundWorker.ReportProgress((int)((i / packListCount) * 100), "Reading TTMP Data...\n"); var dataOffset = 0; using (var br = new BinaryReader(ms)) { //backgroundWorker.ReportProgress((int)((i / packListCount) * 100), "Begining Import...\n"); foreach (var mpi in pack) { currentImport = mpi.Name + "...."; backgroundWorker.ReportProgress((int)((i / packListCount) * 100), currentImport); JsonEntry modEntry = null; bool inModList = false; bool overwrite = false; int lineNum = 0; int originalOffset = 0; int offset = 0; byte[] dataBytes = new byte[mpi.mEntry.ModSize]; List <byte> modDataList = new List <byte>(); br.BaseStream.Seek(dataOffset, SeekOrigin.Begin); modDataList.AddRange(br.ReadBytes(mpi.mEntry.ModSize)); try { foreach (var line in modFileLines) { modEntry = JsonConvert.DeserializeObject <JsonEntry>(line); if (modEntry.fullPath.Equals(mpi.mEntry.FullPath)) { inModList = true; break; } lineNum++; } var datNum = int.Parse(Info.ModDatDict[mpi.mEntry.DatFile]); var modDatPath = string.Format(Info.datDir, mpi.mEntry.DatFile, datNum); var fileLength = new FileInfo(modDatPath).Length; while (fileLength + mpi.mEntry.ModSize >= 2000000000) { datNum += 1; modDatPath = string.Format(Info.datDir, mpi.mEntry.DatFile, datNum); if (!File.Exists(modDatPath)) { CreateDat.MakeNewDat(mpi.mEntry.DatFile); } fileLength = new FileInfo(modDatPath).Length; } //is in modlist and size of new mod is less than or equal to existing mod size if (inModList && mpi.mEntry.ModSize <= modEntry.modSize) { int sizeDiff = modEntry.modSize - modDataList.Count; datNum = ((modEntry.modOffset / 8) & 0x0F) / 2; modDatPath = string.Format(Info.datDir, modEntry.datFile, datNum); var datOffsetAmount = 16 * datNum; using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(modDatPath))) { bw.BaseStream.Seek(modEntry.modOffset - datOffsetAmount, SeekOrigin.Begin); bw.Write(modDataList.ToArray()); bw.Write(new byte[sizeDiff]); } Helper.UpdateIndex(modEntry.modOffset, mpi.mEntry.FullPath, mpi.mEntry.DatFile); Helper.UpdateIndex2(modEntry.modOffset, mpi.mEntry.FullPath, mpi.mEntry.DatFile); offset = modEntry.modOffset; overwrite = true; } if (!overwrite) { using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(modDatPath))) { bw.BaseStream.Seek(0, SeekOrigin.End); while ((bw.BaseStream.Position & 0xFF) != 0) { bw.Write((byte)0); } int eof = (int)bw.BaseStream.Position + modDataList.Count; while ((eof & 0xFF) != 0) { modDataList.AddRange(new byte[16]); eof = eof + 16; } var datOffsetAmount = 16 * datNum; offset = (int)bw.BaseStream.Position + datOffsetAmount; if (offset != 0) { bw.Write(modDataList.ToArray()); } else { FlexibleMessageBox.Show("There was an issue obtaining the .dat4 offset to write data to, try importing again. " + "\n\n If the problem persists, please submit a bug report.", "ImportModel Error " + Info.appVersion, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } int oldOffset = Helper.UpdateIndex(offset, mpi.mEntry.FullPath, mpi.mEntry.DatFile) * 8; Helper.UpdateIndex2(offset, mpi.mEntry.FullPath, mpi.mEntry.DatFile); //is in modlist and size of new mod is larger than existing mod size if (inModList && mpi.mEntry.ModSize > modEntry.modSize) { oldOffset = modEntry.originalOffset; JsonEntry replaceEntry = new JsonEntry() { category = String.Empty, name = String.Empty, fullPath = String.Empty, originalOffset = 0, modOffset = modEntry.modOffset, modSize = modEntry.modSize, datFile = mpi.mEntry.DatFile }; modFileLines[lineNum] = JsonConvert.SerializeObject(replaceEntry); File.WriteAllLines(Properties.Settings.Default.Modlist_Directory, modFileLines); } JsonEntry jsonEntry = new JsonEntry() { category = mpi.Category, name = mpi.Name, fullPath = mpi.mEntry.FullPath, originalOffset = oldOffset, modOffset = offset, modSize = mpi.mEntry.ModSize, datFile = mpi.mEntry.DatFile }; try { modFileLines.Add(JsonConvert.SerializeObject(jsonEntry)); File.WriteAllLines(Properties.Settings.Default.Modlist_Directory, modFileLines); } catch (Exception ex) { FlexibleMessageBox.Show("Error Accessing .modlist File \n" + ex.Message, "ImportModel Error " + Info.appVersion, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (Exception ex) { FlexibleMessageBox.Show("There was an error in importing. \n" + ex.Message, "ImportModPack Error " + Info.appVersion, MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.WriteLine(ex.StackTrace); } i++; backgroundWorker.ReportProgress((int)((i / packListCount) * 100), "Done."); dataOffset += mpi.mEntry.ModSize; } } } } stream.Dispose(); stream.Close(); } } } } catch (Exception ex) { FlexibleMessageBox.Show("Error opening TexTools ModPack file. \n" + ex.Message, "ImportModPack Error " + Info.appVersion, MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.WriteLine(ex.StackTrace); } }
public ImportModPack(string modPackPath) { InitializeComponent(); dt.Tick += new EventHandler(dt_Tick); packPath = modPackPath; InfoHeader.Content = "The following Mods will be installed."; List <ModPackItems> mpiList = new List <ModPackItems>(); List <ModPackJson> mpjList = new List <ModPackJson>(); ModPackInfo mpInfo; try { using (ZipArchive archive = ZipFile.OpenRead(packPath)) { foreach (var entry in archive.Entries) { if (entry.FullName.EndsWith(".mpl")) { using (StreamReader sr = new StreamReader(entry.Open())) { var line = sr.ReadLine(); if (line.ToLower().Contains("version")) { mpInfo = JsonConvert.DeserializeObject <ModPackInfo>(line); } else { mpjList.Add(deserializeModPackJsonLine(line)); } while (sr.Peek() >= 0) { line = sr.ReadLine(); mpjList.Add(deserializeModPackJsonLine(line)); } } } } } } catch (Exception ex) { FlexibleMessageBox.Show("Error opening TexTools ModPack file. \n" + ex.Message, "ImportModPack Error " + Info.appVersion, MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.WriteLine(ex.StackTrace); } float totalModSize = 0; foreach (var mpi in mpjList) { var r = "-"; var num = "-"; var type = "-"; if (mpi.FullPath.Contains("ui/")) { r = "UI"; } else if (mpi.FullPath.Contains("monster")) { r = "Monster"; } else if (mpi.FullPath.Contains(".tex") || mpi.FullPath.Contains(".mdl")) { if (mpi.FullPath.Contains("accessory") || mpi.FullPath.Contains("weapon") || mpi.FullPath.Contains("/common/")) { r = Strings.All; } else { if (mpi.FullPath.Contains("demihuman")) { r = "DemiHuman"; } else if (mpi.FullPath.Contains("/v")) { r = mpi.FullPath.Substring(mpi.FullPath.IndexOf("_c") + 2, 4); r = Info.IDRace[r]; } else { r = mpi.FullPath.Substring(mpi.FullPath.IndexOf("/c") + 2, 4); r = Info.IDRace[r]; } } if (mpi.FullPath.Contains("/human/") && mpi.FullPath.Contains("/body/")) { var t = mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("/b") + 2, 4); num = int.Parse(t).ToString(); } if (mpi.FullPath.Contains("/face/")) { var t = mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("/f") + 2, 4); num = int.Parse(t).ToString(); if (mpi.FullPath.Contains(".tex")) { type = FaceTypes[mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("_") - 3, 3)]; } } if (mpi.FullPath.Contains("/hair/")) { var t = mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("/h") + 2, 4); num = int.Parse(t).ToString(); if (mpi.FullPath.Contains(".tex")) { type = HairTypes[mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("_") - 3, 3)]; } } if (mpi.FullPath.Contains("decal_face")) { var length = mpi.FullPath.LastIndexOf(".") - (mpi.FullPath.LastIndexOf("_") + 1); var t = mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("_") + 1, length); num = int.Parse(t).ToString(); } if (mpi.FullPath.Contains("decal_equip")) { var t = mpi.FullPath.Substring(mpi.FullPath.LastIndexOf("_") + 1, 3); try { num = int.Parse(t).ToString(); } catch { if (mpi.FullPath.Contains("stigma")) { num = "stigma"; } else { num = "Error"; } } } } var m = "3D"; if (mpi.FullPath.Contains("ui/")) { var t = mpi.FullPath.Substring(mpi.FullPath.IndexOf("/") + 1); m = t.Substring(0, t.IndexOf("/")); } else if (mpi.FullPath.Contains(".tex")) { m = GetMapName(mpi.FullPath); } else if (mpi.FullPath.Contains(".mtrl")) { m = "ColorSet"; } totalModSize += mpi.ModSize; var isActive = Helper.IsActive(mpi.FullPath, mpi.DatFile); mpiList.Add(new ModPackItems { Name = mpi.Name, Category = mpi.Category, Race = r, Part = type, Num = num, Map = m, Active = isActive, mEntry = mpi }); } mpiList.Sort(); listView.ItemsSource = mpiList; listView.SelectAll(); modCount.Content = mpiList.Count; string sizeSuffix = " Bytes"; if (totalModSize > 1024 && totalModSize < 1048576) { totalModSize = totalModSize / 1024; sizeSuffix = " KB"; } else if (totalModSize > 1048576 && totalModSize < 1073741824) { totalModSize = totalModSize / 1048576; sizeSuffix = " MB"; } else if (totalModSize > 1073741824) { totalModSize = totalModSize / 1073741824; sizeSuffix = " GB"; } modSize.Content = totalModSize.ToString("0.##") + sizeSuffix; }
/// <summary> /// Unpacks a <paramref name="stream"/> to a Config. /// </summary> public static async Task <Config> Unpack(Stream stream) { var config = new Config(); using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, false)) { // readme.md (not essential) try { config.Readme = ReadStringFromZipEntry(archive, "readme.md"); } catch { Console.WriteLine($"Could not read readme.md in config with id {config.Id}"); } // metadata.json try { config.Metadata = JsonConvert.DeserializeObject <ConfigMetadata>(ReadStringFromZipEntry(archive, "metadata.json"), jsonSettings); } catch { throw new FileNotFoundException("File not found inside the opk archive", "metadata.json"); } // settings.json try { config.Settings = JsonConvert.DeserializeObject <ConfigSettings>(ReadStringFromZipEntry(archive, "settings.json"), jsonSettings); } catch { throw new FileNotFoundException("File not found inside the opk archive", "settings.json"); } if (archive.Entries.Any(e => e.Name.Contains("script.cs"))) { // script.cs try { config.CSharpScript = ReadStringFromZipEntry(archive, "script.cs"); config.Mode = ConfigMode.CSharp; } catch { throw new FileLoadException("Could not load the file from the opk archive", "script.cs"); } } else if (archive.Entries.Any(e => e.Name.Contains("build.dll"))) { // build.dll try { config.DLLBytes = ReadBytesFromZipEntry(archive, "build.dll"); config.Mode = ConfigMode.DLL; } catch { throw new FileLoadException("Could not load the file from the opk archive", "build.dll"); } } else { // script.loli try { config.LoliCodeScript = ReadStringFromZipEntry(archive, "script.loli"); config.Mode = ConfigMode.LoliCode; } catch { throw new FileLoadException("Could not load the file from the opk archive", "script.loli"); } } } config.UpdateHashes(); return(await Task.FromResult(config)); }
private static string ReadStringFromZipEntry(ZipArchive archive, string path) => Encoding.UTF8.GetString(ReadBytesFromZipEntry(archive, path));
private static void ExtractContracts <TEntity, TContract>(ISessionWrapper session, ZipArchive zip, Func <QueryOverProjectionBuilder <TEntity>, QueryOverProjectionBuilder <TEntity> > fieldBuilder) where TEntity : class where TContract : class { var records = session.QueryOver <TEntity>() .SelectList(fieldBuilder) .List <object[]>(); var jsonSerializer = new JsonSerializer { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Include }; var zipLock = new object(); // We should be able to get a bit of a perf boost using parallelism. However, since we're locking on // writing to the zip archive, using any more than 2 threads would be pointless in this case Parallel.ForEach(records, new ParallelOptions { MaxDegreeOfParallelism = 2 }, record => { string zipEntryName = record[0].ToString(); int contractLen = (int)record[1]; byte[] contractBinary = (byte[])record[2]; if (contractLen > 0 && contractBinary != null) { TContract contract = CompressionHelper.DeserializeObject <TContract>(contractBinary, contractLen); lock (zipLock) { ZipArchiveEntry archiveEntry = zip.CreateEntry(zipEntryName, CompressionLevel.Optimal); using (StreamWriter writer = new StreamWriter(archiveEntry.Open(), Encoding.UTF8)) { jsonSerializer.Serialize(writer, contract); } } } }); }
/// <inheritdoc /> public override void Build(BuildOptions options) { var root = options.IntermediateFolder; var packagePath = Path.Combine(root, "package.zip"); var filesToKeep = new[] { "freetype.Build.cs", }; // Get the source Downloader.DownloadFileFromUrlToPath("https://sourceforge.net/projects/freetype/files/freetype2/2.10.0/ft2100.zip/download", packagePath); using (ZipArchive archive = ZipFile.Open(packagePath, ZipArchiveMode.Read)) { archive.ExtractToDirectory(root); root = Path.Combine(root, archive.Entries.First().FullName); } var configurationMsvc = "Release Static"; var binariesToCopyMsvc = new[] { "freetype.lib", "freetype.pdb", }; var vsSolutionPath = Path.Combine(root, "builds", "windows", "vc2010", "freetype.sln"); var vcxprojPath = Path.Combine(root, "builds", "windows", "vc2010", "freetype.vcxproj"); var vcxprojContents = File.ReadAllText(vcxprojPath); var libraryFileName = "libfreetype.a"; vcxprojContents = vcxprojContents.Replace("<RuntimeLibrary>MultiThreaded</RuntimeLibrary>", "<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>"); vcxprojContents = vcxprojContents.Replace("<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>", "<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>"); foreach (var platform in options.Platforms) { switch (platform) { case TargetPlatform.Windows: { // Fix the MSVC project settings for Windows PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "8.1", "140"); // Build for Win64 Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.UWP: { // Fix the MSVC project settings for UWP PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "10.0.17763.0", "v141"); // Build for UWP x64 Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.XboxOne: { // Fix the MSVC project settings for Xbox One PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "10.0.17763.0", "v141"); // Build for Xbox One x64 Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.Linux: { var envVars = new Dictionary <string, string> { { "CC", "clang-7" }, { "CC_FOR_BUILD", "clang-7" } }; var buildDir = Path.Combine(root, "build"); // Fix scripts Utilities.Run("sed", "-i -e \'s/\r$//\' autogen.sh", null, root, Utilities.RunOptions.None, envVars); Utilities.Run("sed", "-i -e \'s/\r$//\' configure", null, root, Utilities.RunOptions.None, envVars); Utilities.Run("chmod", "+x autogen.sh", null, root, Utilities.RunOptions.None); Utilities.Run("chmod", "+x configure", null, root, Utilities.RunOptions.None); Utilities.Run(Path.Combine(root, "autogen.sh"), null, null, root, Utilities.RunOptions.Default, envVars); // Disable using libpng even if it's found on the system var cmakeFile = Path.Combine(root, "CMakeLists.txt"); File.WriteAllText(cmakeFile, File.ReadAllText(cmakeFile) .Replace("find_package(PNG)", "") .Replace("find_package(ZLIB)", "") .Replace("find_package(BZip2)", "") ); // Build for Linux SetupDirectory(buildDir, true); var toolchain = UnixToolchain.GetToolchainName(platform, TargetArchitecture.x64); Utilities.Run("cmake", string.Format("-G \"Unix Makefiles\" -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DFT_WITH_BZIP2=OFF -DFT_WITH_ZLIB=OFF -DFT_WITH_PNG=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER_TARGET={0} ..", toolchain), null, buildDir, Utilities.RunOptions.None, envVars); Utilities.Run("cmake", "--build .", null, buildDir, Utilities.RunOptions.None, envVars); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); Utilities.FileCopy(Path.Combine(buildDir, libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } case TargetPlatform.PS4: { // Get the build data files Utilities.DirectoryCopy( Path.Combine(GetBinariesFolder(options, platform), "Data", "freetype"), Path.Combine(root, "builds", "PS4"), false, true); // Build for PS4 var solutionPath = Path.Combine(root, "builds", "PS4", "freetype.sln"); Deploy.VCEnvironment.BuildSolution(solutionPath, "Release", "ORBIS"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); Utilities.FileCopy(Path.Combine(root, "lib", "PS4", libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } case TargetPlatform.XboxScarlett: { // Fix the MSVC project settings for Xbox Scarlett PatchWindowsTargetPlatformVersion(vcxprojPath, vcxprojContents, "10.0.19041.0", "v142"); // Build for Xbox Scarlett Deploy.VCEnvironment.BuildSolution(vsSolutionPath, configurationMsvc, "x64"); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.x64); foreach (var filename in binariesToCopyMsvc) { Utilities.FileCopy(Path.Combine(root, "objs", "x64", configurationMsvc, filename), Path.Combine(depsFolder, filename)); } break; } case TargetPlatform.Android: { var buildDir = Path.Combine(root, "build"); // Disable using libpng even if it's found on the system var cmakeFile = Path.Combine(root, "CMakeLists.txt"); File.WriteAllText(cmakeFile, File.ReadAllText(cmakeFile) .Replace("find_package(PNG)", "") .Replace("find_package(ZLIB)", "") .Replace("find_package(BZip2)", "") ); // Build for Android SetupDirectory(buildDir, true); RunCmake(buildDir, TargetPlatform.Android, TargetArchitecture.ARM64, ".. -DFT_WITH_BZIP2=OFF -DFT_WITH_ZLIB=OFF -DFT_WITH_PNG=OFF -DCMAKE_BUILD_TYPE=Release"); Utilities.Run("cmake", "--build .", null, buildDir, Utilities.RunOptions.None); var depsFolder = GetThirdPartyFolder(options, platform, TargetArchitecture.ARM64); Utilities.FileCopy(Path.Combine(buildDir, libraryFileName), Path.Combine(depsFolder, libraryFileName)); break; } } } // Backup files var srcIncludePath = Path.Combine(root, "include", "freetype"); var dstIncludePath = Path.Combine(options.ThirdPartyFolder, "freetype"); foreach (var filename in filesToKeep) { var src = Path.Combine(dstIncludePath, filename); var dst = Path.Combine(options.IntermediateFolder, filename + ".tmp"); Utilities.FileCopy(src, dst); } // Setup headers directory SetupDirectory(dstIncludePath, true); // Deploy header files and restore files Utilities.DirectoryCopy(srcIncludePath, dstIncludePath, true, true); Utilities.FileCopy(Path.Combine(root, "include", "ft2build.h"), Path.Combine(dstIncludePath, "ft2build.h")); Utilities.FileCopy(Path.Combine(root, "docs", "LICENSE.TXT"), Path.Combine(dstIncludePath, "LICENSE.TXT")); foreach (var filename in filesToKeep) { var src = Path.Combine(options.IntermediateFolder, filename + ".tmp"); var dst = Path.Combine(dstIncludePath, filename); Utilities.FileCopy(src, dst); } }
private async Task InstallMod(Mod mod, string directory) { int filesCount = 0; string downloadLink = null; foreach (Mod.DownloadLink link in mod.downloads) { filesCount = link.hashMd5.Length; if (link.type == "universal") { downloadLink = link.url; break; } else if (link.type.ToLower() == App.BeatSaberInstallType.ToLower()) { downloadLink = link.url; break; } } if (string.IsNullOrEmpty(downloadLink)) { System.Windows.MessageBox.Show(string.Format((string)FindResource("Mods:ModDownloadLinkMissing"), mod.name)); return; } while (true) { List <ZipArchiveEntry> files = new List <ZipArchiveEntry>(filesCount); using (Stream stream = await DownloadMod(Utils.Constants.BeatModsURL + downloadLink)) using (ZipArchive archive = new ZipArchive(stream)) { foreach (ZipArchiveEntry file in archive.Entries) { string fileDirectory = Path.GetDirectoryName(Path.Combine(directory, file.FullName)); if (!Directory.Exists(fileDirectory)) { Directory.CreateDirectory(fileDirectory); } if (!string.IsNullOrEmpty(file.Name)) { foreach (Mod.DownloadLink download in mod.downloads) { foreach (Mod.FileHashes fileHash in download.hashMd5) { using (Stream fileStream = file.Open()) { if (fileHash.hash == Utils.CalculateMD5FromStream(fileStream)) { files.Add(file); break; } } } } } } if (files.Count == filesCount) { foreach (ZipArchiveEntry file in files) { await ExtractFile(file, Path.Combine(directory, file.FullName), 3.0, mod.name, 10); } break; } } } if (App.CheckInstalledMods) { mod.ListItem.IsInstalled = true; mod.ListItem.InstalledVersion = mod.version; mod.ListItem.InstalledModInfo = mod; } }
/// <summary> /// Reads a single archiveFile from a Zip Archive. Should only be used by ZipArchive. /// </summary> /// <returns>A ZipArchiveFile representing the archiveFile read from the archive.</returns> internal static ZipArchiveFile Read(ZipArchive archive) { Stream reader = archive.fromStream; ByteBuffer header = new ByteBuffer(30); int count = header.ReadContentsFrom(reader); if (count == 0) return null; //Local file header: // //local file header signature 4 bytes (0x04034b50) //version needed to extract 2 bytes //general purpose bit flag 2 bytes //compression method 2 bytes //last mod file time 2 bytes //last mod file date 2 bytes //crc-32 4 bytes //compressed size 4 bytes //uncompressed size 4 bytes //file name length 2 bytes //extra field length 2 bytes // //file name (variable size) //extra field (variable size) uint fileSignature = header.ReadUInt32(); if (fileSignature != SignatureFileEntry) { if (fileSignature != SignatureArchiveDirectory) throw new ApplicationException("Bad ZipFile Header"); return null; } ushort versionNeededToExtract = header.ReadUInt16(); if (versionNeededToExtract > MaximumVersionExtractable) throw new ApplicationException("Zip file requires unsupported features"); header.SkipBytes(2); // general purpose bit flag ZipArchiveFile newEntry = new ZipArchiveFile(archive, null); newEntry.compressionMethod = (CompressionMethod)header.ReadUInt16(); newEntry.lastWriteTime = DosTimeToDateTime(header.ReadUInt32()); newEntry.crc32 = header.ReadUInt32(); newEntry.compressedLength = checked((int)header.ReadUInt32()); newEntry.length = header.ReadUInt32(); int fileNameLength = checked((int)header.ReadUInt16()); byte[] fileNameBuffer = new byte[fileNameLength]; int fileNameCount = reader.Read(fileNameBuffer, 0, fileNameLength); newEntry.name = Encoding.UTF8.GetString(fileNameBuffer).Replace('/', Path.DirectorySeparatorChar); archive.entries[newEntry.name] = newEntry; if (count != header.Length || fileNameCount != fileNameLength || fileNameLength == 0 || newEntry.LastWriteTime.Ticks == 0) throw new ApplicationException("Bad Zip File Header"); if (newEntry.Name.IndexOfAny(invalidPathChars) >= 0) throw new ApplicationException("Invalid File Name"); if (newEntry.compressionMethod != CompressionMethod.None && newEntry.compressionMethod != CompressionMethod.Deflate) throw new ApplicationException("Unsupported compression mode " + newEntry.compressionMethod); if (archive.IsReadOnly && reader.CanSeek) { // Optimization: we can defer reading in the data in the common case of a read-only archive. // by simply remembering where the data is and fetching it on demand. This is nice because // we only hold on to memory of data we are actually operating on. (instead of the whole archive) // // Because uncompresseData is null, we know that we fetch it from the archive 'fromStream'. newEntry.positionOfCompressedDataInArchive = archive.fromStream.Position; reader.Seek(newEntry.compressedLength, SeekOrigin.Current); } else { // We may be updating the archive in place, so we need to copy the data out. newEntry.compressedData = new byte[newEntry.compressedLength]; reader.Read(newEntry.compressedData, 0, (int)newEntry.compressedLength); } #if DEBUG newEntry.Validate(); #endif return newEntry; }
/// <summary> /// Extracts a file from the application bundle. /// </summary> /// <param name="pathInArchive">The relative path of the file inside the application bundle.</param> /// <returns>The full path to the extracted file.</returns> public string ExtractFileFromXap(string pathInArchive) { string result = string.Empty; // Do not use "using" for the FileStream. The ZipArchive will close/dispose the stream unless // we specify otherwise. FileStream appArchiveFileStream = new FileStream(this.ArchiveFilePath, FileMode.Open, FileAccess.Read); using (ZipArchive zipArchive = new ZipArchive(appArchiveFileStream, ZipArchiveMode.Read)) { string tempFileName = Path.GetTempFileName(); ZipArchiveEntry iconFileEntry = zipArchive.GetEntry(pathInArchive); using (Stream iconFileStream = iconFileEntry.Open()) { if (iconFileStream == null) { throw new ConsoleDriverException("Could not get file stream for icon from application archive."); } using (FileStream iconOutputFileStream = new FileStream(tempFileName, FileMode.Create)) { iconFileStream.CopyTo(iconOutputFileStream); } } result = tempFileName; } return result; }
private async Task <Establishment[]> ReadEstablishments(ZipArchive zip) { return(await ReadFromZip <Establishment, EstablishmentFileParser>(zip, "Eapim_Daily_Download.csv")); }
/// <summary> /// Creates a ZipEntry of the passed node and its childs to the passed zip file. /// </summary> /// <param name="zip">The zip file to add the new zip entry to.</param> /// <param name="node">The node to create a zip entry for.</param> /// <param name="processedNodeCount">Count of the processed nodes (for recursive calls only).</param> /// <returns>Count of the processed nodes.</returns> private static int CreateZipEntry(ZipArchive zip, ModNode node, int processedNodeCount = 0) { string absPath = KSPPathHelper.GetAbsolutePath(node.Destination); string gameDataPath = KSPPathHelper.GetPath(KSPPaths.GameData); string path = absPath.Replace(gameDataPath + Path.DirectorySeparatorChar, string.Empty); if (node.IsFile && node.IsInstalled) zip.AddEntry(path, absPath); foreach (ModNode child in node.Nodes) processedNodeCount = CreateZipEntry(zip, child, processedNodeCount); return processedNodeCount; }
private async Task <GroupLink[]> ReadGroupLinks(ZipArchive zip) { return(await ReadFromZip <GroupLink, GroupLinkFileParser>(zip, "groupLinks.csv")); }
public static void WriteToStream(Pass pass, Stream stream, X509Certificate2 appleCert, X509Certificate2 passCert) { using (archive = new ZipArchive(stream, ZipArchiveMode.Update, true)) { AddEntry(@"pass.json", ToJson(pass)); AddAssetEntry(@"icon.png", pass.icon); AddAssetEntry(@"*****@*****.**", pass.icon2x); AddAssetEntry(@"*****@*****.**", pass.icon3x); AddAssetEntry(@"logo.png", pass.logo); AddAssetEntry(@"*****@*****.**", pass.logo2x); AddAssetEntry(@"*****@*****.**", pass.logo3x); AddAssetEntry(@"background.png", pass.background); AddAssetEntry(@"*****@*****.**", pass.background2x); AddAssetEntry(@"*****@*****.**", pass.background3x); AddAssetEntry(@"footer.png", pass.footer); AddAssetEntry(@"*****@*****.**", pass.footer2x); AddAssetEntry(@"*****@*****.**", pass.footer3x); AddAssetEntry(@"strip.png", pass.strip); AddAssetEntry(@"*****@*****.**", pass.strip2x); AddAssetEntry(@"*****@*****.**", pass.strip3x); AddAssetEntry(@"thumbnail.png", pass.thumbnail); AddAssetEntry(@"*****@*****.**", pass.thumbnail2x); AddAssetEntry(@"*****@*****.**", pass.thumbnail3x); if (pass.localizations != null && pass.localizations.Count > 0) { foreach (var localization in pass.localizations) { Func <string, string> entryName = name => @"{0}/{1}".FormatWith("{0}.lproj".FormatWith(localization.culture), name); var passStrings = new List <string>(); if (localization.values != null) { foreach (var key in localization.values.Keys) { passStrings.Add(@"""{0}"" = ""{1}"";".FormatWith(key, localization.values[key])); } AddEntry(entryName("pass.strings"), passStrings.Join("\n")); } AddAssetEntry(entryName("icon.png"), localization.icon); AddAssetEntry(entryName("*****@*****.**"), localization.icon2x); AddAssetEntry(entryName("*****@*****.**"), localization.icon3x); AddAssetEntry(entryName("logo.png"), localization.logo); AddAssetEntry(entryName("*****@*****.**"), localization.logo2x); AddAssetEntry(entryName("*****@*****.**"), localization.logo3x); AddAssetEntry(entryName("background.png"), localization.background); AddAssetEntry(entryName("*****@*****.**"), localization.background2x); AddAssetEntry(entryName("*****@*****.**"), localization.background3x); AddAssetEntry(entryName("footer.png"), localization.footer); AddAssetEntry(entryName("*****@*****.**"), localization.footer2x); AddAssetEntry(entryName("*****@*****.**"), localization.footer3x); AddAssetEntry(entryName("strip.png"), localization.strip); AddAssetEntry(entryName("*****@*****.**"), localization.strip2x); AddAssetEntry(entryName("*****@*****.**"), localization.strip3x); AddAssetEntry(entryName("thumbnail.png"), localization.thumbnail); AddAssetEntry(entryName("*****@*****.**"), localization.thumbnail2x); AddAssetEntry(entryName("*****@*****.**"), localization.thumbnail3x); } } var manifestJson = GenerateManifest().ToJson(); AddEntry(@"manifest.json", manifestJson); AddEntry(@"signature", GenerateSignature(manifestJson.ToUtf8Bytes(), appleCert, passCert)); } }
public static void FixInvalidUri(Stream fs, Func <string, Uri> invalidUriHandler) { XNamespace relNs = "http://schemas.openxmlformats.org/package/2006/relationships"; using (var za = new ZipArchive(fs, ZipArchiveMode.Update)) { foreach (ZipArchiveEntry entry in za.Entries.ToList()) { if (!entry.Name.EndsWith(".rels")) { continue; } var replaceEntry = false; XDocument entryXDoc; using (Stream entryStream = entry.Open()) { try { entryXDoc = XDocument.Load(entryStream); if (entryXDoc.Root != null && entryXDoc.Root.Name.Namespace == relNs) { IEnumerable <XElement> urisToCheck = entryXDoc .Descendants(relNs + "Relationship") .Where(r => r.Attribute("TargetMode") != null && (string)r.Attribute("TargetMode") == "External"); foreach (XElement rel in urisToCheck) { var target = (string)rel.Attribute("Target"); if (target != null) { try { var unused = new Uri(target); } catch (UriFormatException) { Uri newUri = invalidUriHandler(target); rel.SetAttributeValue("Target", newUri.ToString()); replaceEntry = true; } } } } } catch (XmlException) { continue; } } if (replaceEntry) { string fullName = entry.FullName; entry.Delete(); ZipArchiveEntry newEntry = za.CreateEntry(fullName); using (var writer = new StreamWriter(newEntry.Open())) using (XmlWriter xmlWriter = XmlWriter.Create(writer)) { entryXDoc.WriteTo(xmlWriter); } } } } }
/// <summary> /// Extracts a zip file to the specified directory. If an exception is thrown during extraction, it is stored in ZipExtractResult. /// </summary> /// <param name="zipPath">Path to zip file</param> /// <param name="extractDirectory">Directory to extract to</param> /// <param name="deleteZip">If true, deletes zip file after extraction</param> /// <param name="overwriteTarget">If true, overwrites existing files with the zip's contents</param> /// <returns></returns> public static ZipExtractResult ExtractZip(string zipPath, string extractDirectory, bool overwriteTarget = true) { if (string.IsNullOrEmpty(zipPath)) { throw new ArgumentNullException(nameof(zipPath)); } if (string.IsNullOrEmpty(extractDirectory)) { throw new ArgumentNullException(nameof(extractDirectory)); } FileInfo zipFile = new FileInfo(zipPath); if (!zipFile.Exists) { throw new ArgumentException($"File at zipPath {zipFile.FullName} does not exist.", nameof(zipPath)); } ZipExtractResult result = new ZipExtractResult { SourceZip = zipPath, ResultStatus = ZipExtractResultStatus.Unknown }; string createdDirectory = null; List <string> createdFiles = new List <string>(); try { //Plugin.log?.Info($"ExtractDirectory is {extractDirectory}"); using (FileStream fs = new FileStream(zipPath, FileMode.Open, FileAccess.Read)) using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Read)) { //Plugin.log?.Info("Zip opened"); //extractDirectory = GetValidPath(extractDirectory, zipArchive.Entries.Select(e => e.Name).ToArray(), shortDirName, overwriteTarget); int longestEntryName = zipArchive.Entries.Select(e => e.Name).Max(n => n.Length); try { extractDirectory = Path.GetFullPath(extractDirectory); // Could theoretically throw an exception: Argument/ArgumentNull/Security/NotSupported/PathTooLong extractDirectory = GetValidPath(extractDirectory, longestEntryName, 3); if (!overwriteTarget && Directory.Exists(extractDirectory)) { int pathNum = 1; string finalPath; do { string append = $" ({pathNum})"; finalPath = GetValidPath(extractDirectory, longestEntryName, append.Length) + append; // padding ensures we aren't continuously cutting off the append value pathNum++; } while (Directory.Exists(finalPath)); extractDirectory = finalPath; } } catch (PathTooLongException ex) { result.Exception = ex; result.ResultStatus = ZipExtractResultStatus.DestinationFailed; return(result); } result.OutputDirectory = extractDirectory; bool extractDirectoryExists = Directory.Exists(extractDirectory); string toBeCreated = extractDirectoryExists ? null : extractDirectory; // For cleanup try { Directory.CreateDirectory(extractDirectory); } catch (Exception ex) { result.Exception = ex; result.ResultStatus = ZipExtractResultStatus.DestinationFailed; return(result); } result.CreatedOutputDirectory = !extractDirectoryExists; createdDirectory = string.IsNullOrEmpty(toBeCreated) ? null : extractDirectory; // TODO: Ordering so largest files extracted first. If the extraction is interrupted, theoretically the song's hash won't match Beat Saver's. foreach (ZipArchiveEntry entry in zipArchive.Entries.OrderByDescending(e => e.Length)) { if (!entry.FullName.Equals(entry.Name)) // If false, the entry is a directory or file nested in one { continue; } string entryPath = Path.Combine(extractDirectory, entry.Name); bool fileExists = File.Exists(entryPath); if (overwriteTarget || !fileExists) { try { entry.ExtractToFile(entryPath, overwriteTarget); createdFiles.Add(entryPath); } catch (InvalidDataException ex) // Entry is missing, corrupt, or compression method isn't supported { Plugin.log?.Error($"Error extracting {extractDirectory}, archive appears to be damaged."); Plugin.log?.Error(ex); result.Exception = ex; result.ResultStatus = ZipExtractResultStatus.SourceFailed; result.ExtractedFiles = createdFiles.ToArray(); } catch (Exception ex) { Plugin.log?.Error($"Error extracting {extractDirectory}"); Plugin.log?.Error(ex); result.Exception = ex; result.ResultStatus = ZipExtractResultStatus.DestinationFailed; result.ExtractedFiles = createdFiles.ToArray(); } if (result.Exception != null) { foreach (string file in createdFiles) { TryDeleteAsync(file).Wait(); } return(result); } } } result.ExtractedFiles = createdFiles.ToArray(); } result.ResultStatus = ZipExtractResultStatus.Success; return(result); #pragma warning disable CA1031 // Do not catch general exception types } catch (InvalidDataException ex) // FileStream is not in the zip archive format. { result.ResultStatus = ZipExtractResultStatus.SourceFailed; result.Exception = ex; return(result); } catch (Exception ex) // If exception is thrown here, it probably happened when the FileStream was opened. #pragma warning restore CA1031 // Do not catch general exception types { Plugin.log?.Error($"Error opening FileStream for {zipPath}"); Plugin.log?.Error(ex); try { if (!string.IsNullOrEmpty(createdDirectory)) { Directory.Delete(createdDirectory, true); } else // TODO: What is this doing here... { foreach (string file in createdFiles) { File.Delete(file); } } } catch (Exception cleanUpException) { // Failed at cleanup Plugin.log?.Debug($"Failed to clean up zip file: {cleanUpException.Message}"); } result.Exception = ex; result.ResultStatus = ZipExtractResultStatus.SourceFailed; return(result); } }
private void ZipList(string fullPath, ZipArchiveEntry e) { using (var archive = new ZipArchive(e.Open())) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.Name != "") { if (entry.Name.Contains(".")) { ext = entry.Name.Substring(entry.Name.LastIndexOf(".")).ToLower(); } else { ext = "null"; } rep = new StringBuilder(@"\"); if (entry.FullName.Contains("/")) { rep.Append($@"{e.FullName}\{entry.FullName.Substring(0, entry.FullName.LastIndexOf("/"))}"); rep.Replace("/", @"\"); } else { rep.Append($"{e.FullName}"); rep.Replace("/", @"\"); } lista.Add($"{entry.Length}\t{fullPath}{rep}\t{entry.Name}\t{ext}"); //await FileWriteAsync($"{Environment.NewLine}{entry.Length}\t{fullPath}{rep}\t{entry.Name}\t{ext}"); //using(System.IO.StreamWriter w = Delimon.Win32.IO.File.AppendText($"{baseDir}lista_arquivos.txt")) { // w.Write($"{Environment.NewLine}{entry.Length}\t{fullPath}{rep}\t{entry.Name}\t{ext}"); // w.Close(); // w.Dispose(); //} //sb.Append($"{Environment.NewLine}{entry.Length}\t{fullPath}{rep}\t{entry.Name}\t{ext}"); if (lista.Count >= 100000) { System.IO.File.AppendAllLines($"{baseDir}lista_arquivos.txt", lista); lista.Clear(); lista.TrimExcess(); } if (ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) { using (var stream = entry.Open()) { using (var ms = new System.IO.MemoryStream()) { stream.CopyTo(ms); ms.Position = 0; CountPdfPages(ms); } } } if (ext.Equals(".doc", StringComparison.OrdinalIgnoreCase) || ext.Equals(".docx", StringComparison.OrdinalIgnoreCase)) { using (var stream = entry.Open()) { using (var ms = new System.IO.MemoryStream()) { stream.CopyTo(ms); ms.Position = 0; CountWordPages(ms); } } } if (ext.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { fn = $@"{fullPath}{rep}"; ZipList(fn, entry); } } } } }
public static bool ExtractAll(ZipArchive zip, string destination, Action <int, int> progressCallback = null, Func <string, string> modifyCallback = null, Func <string, bool> deleteCallback = null, bool forceUpdate = true) { int i = 0; int total = (int)zip.EntryCount; bool updated = false; HashSet <string> files = new HashSet <string> (); foreach (var entry in zip) { progressCallback?.Invoke(i++, total); if (entry.FullName.Contains("/__MACOSX/") || entry.FullName.EndsWith("/__MACOSX", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith("/.DS_Store", StringComparison.OrdinalIgnoreCase)) { continue; } var fullName = modifyCallback?.Invoke(entry.FullName) ?? entry.FullName; if (entry.IsDirectory) { try { Directory.CreateDirectory(Path.Combine(destination, fullName)); } catch (NotSupportedException ex) { //NOTE: invalid paths, such as `:` on Windows can cause this throw new NotSupportedException($"Invalid zip entry `{fullName}` found in archive.", ex); } continue; } try { Directory.CreateDirectory(Path.Combine(destination, Path.GetDirectoryName(fullName))); } catch (NotSupportedException ex) { //NOTE: invalid paths, such as `:` on Windows can cause this throw new NotSupportedException($"Invalid zip entry `{fullName}` found in archive.", ex); } var outfile = Path.GetFullPath(Path.Combine(destination, fullName)); files.Add(outfile); var dt = File.Exists(outfile) ? File.GetLastWriteTimeUtc(outfile) : DateTime.MinValue; if (forceUpdate || entry.ModificationTime > dt) { try { entry.Extract(destination, fullName, FileMode.Create); } catch (PathTooLongException) { throw new PathTooLongException($"Could not extract \"{fullName}\" to \"{outfile}\". Path is too long."); } updated = true; } } foreach (var file in Directory.GetFiles(destination, "*.*", SearchOption.AllDirectories)) { var outfile = Path.GetFullPath(file); if (outfile.Contains("/__MACOSX/") || outfile.EndsWith("__AndroidLibraryProjects__.zip", StringComparison.OrdinalIgnoreCase) || outfile.EndsWith("/__MACOSX", StringComparison.OrdinalIgnoreCase) || outfile.EndsWith("/.DS_Store", StringComparison.OrdinalIgnoreCase)) { continue; } if (!files.Contains(outfile) && !(deleteCallback?.Invoke(outfile) ?? true)) { File.Delete(outfile); updated = true; } } return(updated); }
public static ZipArchiveEntry[] BatchChapterGetMT(Chapter[] chapters, Book host, string dir, int tid = 0, Action <int, string> statusUpdate = null) { Stream fs = new MemoryStream(); ZipArchive zappo = new ZipArchive(fs, ZipArchiveMode.Update); WebClient wc = new WebClient(); HtmlDocument docu = new HtmlDocument(); int f = 0; Chapter lastChp = null; foreach (Chapter chp in chapters) { f++; chp.name = chp.name.RemoveSpecialCharacters(); if (!chp.name.Any(char.IsDigit)) { throw new Exception("Chapter lacks chapter number (retry without -mt): " + chp.name); } chp.name = chp.name.Replace(' ', '_'); if (chp.name.ToLower().Contains("volume")) { chp.name = new string(chp.name.Skip(7).ToArray()); int integrals = chp.name.ToArray().LeadingIntegralCount(); chp.name = new string(chp.name.Skip(integrals + 1).ToArray()); chp.chapterNum = chp.name.ToArray().FirstLIntegralCount(); } if (chp.name[0] == '-') { chp.chapterNum = chp.chapterNum * -1; } if (lastChp != null) { if (chp.chapterNum - 1 != lastChp.chapterNum) { host.sortedTrustFactor = true; // Consistency lost, chapter list can not be trusted. } } lastChp = chp; double prg = (double)f / (double)chapters.Length; if (statusUpdate != null) { statusUpdate(tid, $"[{new string('#', (int)(prg * 10))}{new string('-', (int)(10 - (prg * 10)))}] {(int)(prg * 100)}% | {f}/{chapters.Length} | Downloading: {chp.name}"); } ADLCore.Alert.ADLUpdates.CallLogUpdate($"[{new string('#', (int)(prg * 10))}{new string('-', (int)(10 - (prg * 10)))}] {(int)(prg * 100)}% | {f}/{chapters.Length} | Downloading: {chp.name}"); if (chp.text != null) { continue; } chp.GetText(docu, wc); using (TextWriter tw = new StreamWriter(zappo.CreateEntry($"Chapters/{chp.name}.txt").Open())) tw.WriteLine(chp.text); docu = new HtmlDocument(); GC.Collect(); } if (statusUpdate != null) { statusUpdate(tid, $"Download finished, {chapters.Length}/{chapters.Length}"); } return(zappo.Entries.ToArray()); }
public static async Task UpdateModeInvalidOperations() { using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(zfile("normal.zip"))) { ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, true); ZipArchiveEntry edeleted = target.GetEntry("first.txt"); Stream s = edeleted.Open(); //invalid ops while entry open Assert.Throws<IOException>(() => edeleted.Open()); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; }); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; }); Assert.Throws<IOException>(() => edeleted.Delete()); s.Dispose(); //invalid ops on stream after entry closed Assert.Throws<ObjectDisposedException>(() => s.ReadByte()); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; }); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; }); edeleted.Delete(); //invalid ops while entry deleted Assert.Throws<InvalidOperationException>(() => edeleted.Open()); Assert.Throws<InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); }); ZipArchiveEntry e = target.GetEntry("notempty/second.txt"); target.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var x = target.Entries; }); Assert.Throws<ObjectDisposedException>(() => target.CreateEntry("dirka")); Assert.Throws<ObjectDisposedException>(() => e.Open()); Assert.Throws<ObjectDisposedException>(() => e.Delete()); Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); }); } }
/// <summary> /// Gets content for every chapter. /// </summary> /// <param name="chapters"></param> /// <returns></returns> public static Chapter[] BatchChapterGet(Chapter[] chapters, string dir, Book host, ref ZipArchive zappo, int tid = 0, Action <int, string> statusUpdate = null, Action updateArchive = null) { WebClient wc = new WebClient(); HtmlDocument docu = new HtmlDocument(); int f = 0; string[] a = null; Chapter lastChp = null; foreach (Chapter chp in chapters) { f++; a = zappo.GetEntriesUnderDirectoryToStandardString("Chapters/"); chp.name = chp.name.RemoveSpecialCharacters(); string tname = chp.name; chp.name = chp.name.Replace(' ', '_'); if (!chp.name.Any(char.IsDigit)) { chp.name += $" {(f - 1)}"; chp.chapterNum = f - 1; } if (lastChp != null) { if (chp.chapterNum - 1 != lastChp.chapterNum) { host.sortedTrustFactor = true; // Consistency lost, chapter list can not be trusted. } } lastChp = chp; double prg = (double)f / (double)chapters.Length; if (statusUpdate != null) { statusUpdate(tid, $"[{new string('#', (int)(prg * 10))}{new string('-', (int)(10 - (prg * 10)))}] {(int)(prg * 100)}% | {f}/{chapters.Length} | Downloading: {tname}"); } ADLCore.Alert.ADLUpdates.CallLogUpdate($"[{new string('#', (int)(prg * 10))}{new string('-', (int)(10 - (prg * 10)))}] {(int)(prg * 100)}% | {f}/{chapters.Length} | Downloading: {tname}"); if (a.Contains($"{chp.name}.txt")) { using (StreamReader sr = new StreamReader(zappo.GetEntry($"Chapters/{chp.name}.txt").Open())) chp.text = sr.ReadToEnd(); continue; } chp.GetText(docu, wc); using (TextWriter tw = new StreamWriter(zappo.CreateEntry($"Chapters/{chp.name}.txt").Open())) tw.WriteLine(chp.text); updateArchive?.Invoke(); docu = new HtmlDocument(); GC.Collect(); } if (statusUpdate != null) { statusUpdate(tid, $"Download finished, {chapters.Length}/{chapters.Length}"); } return(chapters); }
public async Task <string> EnsureTargetReleaseAsync(string targetRelease, IProgressReceiver progressReceiver) { var targetVersion = targetRelease; //manifest.Latest.Release; string assetsZipSavePath = Path.Combine("assets", $"java-{targetVersion}.zip"); if (_storage.Exists(assetsZipSavePath)) { Log.Info("Java assets already up to date!"); return(assetsZipSavePath); } if (_storage.TryReadString(CurrentVersionStorageKey, out var currentVersion)) { if (currentVersion == targetVersion) { if (_storage.Exists(assetsZipSavePath)) { Log.Info("MCJava Assets Up to date!"); return(assetsZipSavePath); } } } if (_storage.Exists(assetsZipSavePath)) { _storage.Delete(assetsZipSavePath); } progressReceiver?.UpdateProgress(0, "Downloading assets..."); var manifest = await GetManifestAsync(); // not latest, update Log.Info($"Downloading MCJava {targetVersion} Assets."); var version = manifest.Versions.FirstOrDefault(v => string.Equals(v.Id, targetVersion, StringComparison.InvariantCultureIgnoreCase)); if (version == null) { Log.Error("Version not found in versions? wut?"); return(assetsZipSavePath); } LauncherMeta launcherMeta; AssetIndex assetIndex; var dirpath = Path.Combine("assets", $"java-{targetVersion}_cache"); if (!_storage.TryGetDirectory(dirpath, out var dir)) { if (_storage.TryCreateDirectory(dirpath)) { if (!_storage.TryGetDirectory(dirpath, out dir)) { return(assetsZipSavePath); } } } // fetch version's json thing using (var httpClient = new HttpClient()) { var launcherMetaJson = await httpClient.GetStringAsync(version.Url); launcherMeta = LauncherMeta.FromJson(launcherMetaJson); // download client, prob usefil? var clientJar = await httpClient.GetByteArrayAsync(launcherMeta.Downloads.Client.Url); using (var clientMs = new MemoryStream(clientJar)) using (ZipArchive clientJarZip = new ZipArchive(clientMs, ZipArchiveMode.Read)) { foreach (var entry in clientJarZip.Entries) { if (!entry.FullName.StartsWith("assets") && entry.FullName != "pack.mcmeta") { continue; } var localpath = Path.Combine(dir.FullName, entry.FullName); if (!_storage.TryGetDirectory(Path.GetDirectoryName(localpath), out _)) { _storage.TryCreateDirectory(Path.GetDirectoryName(localpath)); // Directory.CreateDirectory(Path.GetDirectoryName(localpath)); } entry.ExtractToFile(localpath, true); Log.Debug($"Extracted Asset '{entry.Name}' (Size: {entry.Length})"); } } // now we only care about asset index soooo... grab that var assetIndexJson = await httpClient.GetStringAsync(launcherMeta.LauncherMetaAssetIndex.Url); assetIndex = AssetIndex.FromJson(assetIndexJson); int target = assetIndex.Objects.Count; int done = 0; foreach (var assetIndexObject in assetIndex.Objects) { // Skip ogg files if (assetIndexObject.Key.EndsWith(".ogg", StringComparison.InvariantCultureIgnoreCase)) { continue; } var assetUrl = AssetResourceUri .Replace("{hash_sub2}", assetIndexObject.Value.Hash.Substring(0, 2)) .Replace("{hash}", assetIndexObject.Value.Hash); progressReceiver?.UpdateProgress(done * (target / 100), "Downloading assets...", assetIndexObject.Key); try { var fileBytes = await httpClient.GetByteArrayAsync(assetUrl); var filename = Path.Combine("assets", assetIndexObject.Key); var localpath = Path.Combine(dir.FullName, filename); if (!_storage.TryGetDirectory(Path.GetDirectoryName(localpath), out _)) { _storage.TryCreateDirectory(Path.GetDirectoryName(localpath)); // Directory.CreateDirectory(Path.GetDirectoryName(localpath)); } // File.WriteAllBytes(localpath, fileBytes); _storage.TryWriteBytes(localpath, fileBytes); Log.Debug($"Downloaded asset '{assetIndexObject.Key}' (Hash: {assetIndexObject.Value.Hash})"); } catch (Exception ex) { Log.Error(ex, $"Failed to download asset '{assetIndexObject.Key}' (Hash: {assetIndexObject.Value.Hash})"); continue; } done++; } } // make new zip m8 using (var ms = new MemoryStream()) { using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, true)) { foreach (var file in dir.EnumerateFiles("*", SearchOption.AllDirectories)) { zip.CreateEntryFromFile(file.FullName, Path.GetRelativePath(dir.FullName, file.FullName)); } } // saving zip m8 ms.Seek(0, SeekOrigin.Begin); var allBytes = ms.ToArray(); _storage.TryWriteBytes(assetsZipSavePath, allBytes); Log.Info($"Written Archive to '{assetsZipSavePath}' (Size: {allBytes.Length})"); } _storage.TryWriteString(CurrentVersionStorageKey, targetVersion); Thread.Sleep(500); dir.Delete(true); return(assetsZipSavePath); }
public void SaveAs(Stream stream, object value) { using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true, Utf8WithBom)) { var packages = DefualtOpenXml.GenerateDefaultOpenXml(archive); var sheetPath = "xl/worksheets/sheet1.xml"; { ZipArchiveEntry entry = archive.CreateEntry(sheetPath); using (var zipStream = entry.Open()) using (StreamWriter writer = new StreamWriter(zipStream, Utf8WithBom)) { if (value == null) { WriteEmptySheet(writer); goto End; } var type = value.GetType(); Type genericType = null; //DapperRow if (value is IEnumerable) { var values = value as IEnumerable; var rowCount = 0; var maxColumnIndex = 0; List <object> keys = new List <object>(); PropertyInfo[] props = null; string mode = null; { foreach (var item in values) //TODO: need to optimize { rowCount = checked (rowCount + 1); if (item != null && mode == null) { if (item is IDictionary <string, object> ) { var item2 = item as IDictionary <string, object>; mode = "IDictionary<string, object>"; maxColumnIndex = item2.Keys.Count; foreach (var key in item2.Keys) { keys.Add(key); } } else if (item is IDictionary) { var item2 = item as IDictionary; mode = "IDictionary"; maxColumnIndex = item2.Keys.Count; foreach (var key in item2.Keys) { keys.Add(key); } } else { mode = "Properties"; genericType = item.GetType(); props = Helpers.GetProperties(genericType); //props = genericType.GetProperties(); if (props.Length == 0) { throw new InvalidOperationException($"Generic Type : {genericType} valid properties count is 0, if you have trouble please issue for me."); } maxColumnIndex = props.Length; } // not re-foreach key point var collection = value as ICollection; if (collection != null) { rowCount = checked ((value as ICollection).Count); break; } continue; } } } if (rowCount == 0) { WriteEmptySheet(writer); goto End; } writer.Write($@"<?xml version=""1.0"" encoding=""utf-8""?><x:worksheet xmlns:x=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"">"); // dimension var maxRowIndex = rowCount + (printHeader && rowCount > 0 ? 1 : 0); //TODO:it can optimize writer.Write($@"<dimension ref=""{GetDimension(maxRowIndex, maxColumnIndex)}""/><x:sheetData>"); //header var yIndex = 1; var xIndex = 1; if (printHeader) { var cellIndex = xIndex; writer.Write($"<x:row r=\"{yIndex.ToString()}\">"); if (props != null) { foreach (var p in props) { var columname = ExcelOpenXmlUtils.ConvertXyToCell(cellIndex, yIndex); writer.Write($"<x:c r=\"{columname}\" t=\"str\"><x:v>{p.Name}</x:v></x:c>"); cellIndex++; } } else { foreach (var key in keys) { var columname = ExcelOpenXmlUtils.ConvertXyToCell(cellIndex, yIndex); writer.Write($"<x:c r=\"{columname}\" t=\"str\"><x:v>{key}</x:v></x:c>"); cellIndex++; } } writer.Write($"</x:row>"); yIndex++; } if (mode == "IDictionary<string, object>") //Dapper Row { GenerateSheetByDapperRow(writer, archive, value as IEnumerable, genericType, rowCount, keys.Cast <string>().ToList(), xIndex, yIndex); } else if (mode == "IDictionary") //IDictionary { GenerateSheetByIDictionary(writer, archive, value as IEnumerable, genericType, rowCount, keys, xIndex, yIndex); } else if (mode == "Properties") { GenerateSheetByProperties(writer, archive, value as IEnumerable, genericType, props, rowCount, keys, xIndex, yIndex); } else { throw new NotImplementedException($"Type {type.Name} & genericType {genericType.Name} not Implemented. please issue for me."); } writer.Write("</x:sheetData></x:worksheet>"); } else if (value is DataTable) { GenerateSheetByDataTable(writer, archive, value as DataTable); } else { throw new NotImplementedException($"Type {type.Name} & genericType {genericType.Name} not Implemented. please issue for me."); } //TODO: } End: packages.Add(sheetPath, new ZipPackageInfo(entry, "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml")); } GenerateContentTypesXml(archive, packages); } }
/// <summary> /// Delete the archiveFile represented by the ZipArchiveFile. The textStream can be in use without conflict. /// Deleting a textStream simply means it will not be persisted when ZipArchive.Close() is called. /// </summary> public void Delete() { if (IsReadOnly) throw new ApplicationException("Archive is ReadOnly"); archive.entries.Remove(name); name = null; archive = null; uncompressedData = null; compressedData = null; }
//private String DecodeStream(string s) { // Encoding defEnc = Encoding.Default; // Encoding isoEnc = Encoding.GetEncoding(850); // byte[] defBytes = defEnc.GetBytes(s); // byte[] isoBytes = Encoding.Convert(defEnc, isoEnc, defBytes); // name = isoEnc.GetString(isoBytes); // return name; //} private void CreateList(string sDir) { try { folder = new Delimon.Win32.IO.DirectoryInfo(sDir); foreach (Delimon.Win32.IO.FileInfo f in folder.GetFiles()) { lista.Add($"{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}"); //await FileWriteAsync($"{Environment.NewLine}{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}"); //using (System.IO.StreamWriter w = Delimon.Win32.IO.File.AppendText($"{baseDir}lista_arquivos.txt")) { // w.Write($"{Environment.NewLine}{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}"); // w.Close(); // w.Dispose(); //} //sb.Append($"{Environment.NewLine}{f.Length}\t{f.DirectoryName}\t{f.Name}\t{f.Extension.ToLower()}"); if (lista.Count >= 100000) { System.IO.File.AppendAllLines($"{baseDir}lista_arquivos.txt", lista); //List<List<String>> l = new List<List<String>>(); //l.Add(lista.ToList()); lista.Clear(); lista.TrimExcess(); } progressBar.Dispatcher.Invoke(() => progressBar.Value++, DispatcherPriority.Background); if (f.Extension.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) { using (var stream = Delimon.Win32.IO.File.OpenRead(f.FullName)) { using (var ms = new System.IO.MemoryStream()) { stream.CopyTo(ms); ms.Position = 0; CountPdfPages(ms); } } } if (f.Extension.Equals(".doc", StringComparison.OrdinalIgnoreCase) || f.Extension.Equals(".docx", StringComparison.OrdinalIgnoreCase)) { using (var stream = Delimon.Win32.IO.File.OpenRead(f.FullName)) { using (var ms = new System.IO.MemoryStream()) { stream.CopyTo(ms); ms.Position = 0; CountWordPages(ms); } } } if (f.Extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { //using (var fs = new System.IO.StreamReader(Delimon.Win32.IO.File.OpenRead(f.FullName), Encoding.GetEncoding(850))) { //using(ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Read, Encoding.GetEncoding(850))) { //ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs); //System.IO.Stream zipStream = zipFile.GetInputStream(fs); fs = Delimon.Win32.IO.File.OpenRead(f.FullName); using (var archive = new ZipArchive(fs, ZipArchiveMode.Read, false, Encoding.GetEncoding(850))) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.Name != "") { if (entry.Name.Contains(".")) { ext = entry.Name.Substring(entry.Name.LastIndexOf(".")).ToLower(); } else { ext = "null"; } rep = new StringBuilder(@"\"); if (entry.FullName.Contains("/")) { rep.Append(entry.FullName.Substring(0, entry.FullName.LastIndexOf("/"))); rep.Replace("/", @"\"); } else { rep.Clear(); } lista.Add($"{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}"); //await FileWriteAsync($"{Environment.NewLine}{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}"); //using (System.IO.StreamWriter w = Delimon.Win32.IO.File.AppendText($"{baseDir}lista_arquivos.txt")) { // w.Write($"{Environment.NewLine}{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}"); // w.Close(); // w.Dispose(); //} //sb.Append($"{Environment.NewLine}{entry.Length}\t{f.FullName}{rep}\t{entry.Name}\t{ext}"); if (lista.Count >= 100000) { System.IO.File.AppendAllLines($"{baseDir}lista_arquivos.txt", lista); lista.Clear(); lista.TrimExcess(); } if (ext.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) { using (var stream = entry.Open()) { using (var ms = new System.IO.MemoryStream()) { stream.CopyTo(ms); ms.Position = 0; CountPdfPages(ms); } } } if (ext.Equals(".doc", StringComparison.OrdinalIgnoreCase) || ext.Equals(".docx", StringComparison.OrdinalIgnoreCase)) { using (var stream = entry.Open()) { using (var ms = new System.IO.MemoryStream()) { stream.CopyTo(ms); ms.Position = 0; CountWordPages(ms); } } } if (ext.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { fn = f.FullName; ZipList(fn, entry); } } } } //} //} } } foreach (string d in Delimon.Win32.IO.Directory.GetDirectories(sDir)) { CreateList(d); } } catch { //System.Windows.Forms.MessageBox.Show($"{exc.Message}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Deletes a file from the application bundle. /// </summary> /// <param name="pathInArchive">The relative path of the file inside the application bundle.</param> public void DeleteFileFromXap(string pathInArchive) { // Do not use "using" for the FileStream. The ZipArchive will close/dispose the stream unless // we specify otherwise. FileStream appArchiveFileStream = new FileStream(this.ArchiveFilePath, FileMode.Open, FileAccess.ReadWrite); using (ZipArchive zipArchive = new ZipArchive(appArchiveFileStream, ZipArchiveMode.Update)) { ZipArchiveEntry iconFileEntry = zipArchive.GetEntry(pathInArchive); iconFileEntry.Delete(); } }
public virtual async Task <IActionResult> GetDownload(Guid orderItemId, bool agree = false) { var orderItem = await _orderService.GetOrderItemByGuid(orderItemId); if (orderItem == null) { return(InvokeHttp404()); } var order = await _orderService.GetOrderByOrderItemId(orderItem.Id); var product = await _productService.GetProductById(orderItem.ProductId); if (!_downloadService.IsDownloadAllowed(order, orderItem, product)) { return(Content("Downloads are not allowed")); } if (_customerSettings.DownloadableProductsValidateUser) { if (_workContext.CurrentCustomer == null) { return(Challenge()); } if (order.CustomerId != _workContext.CurrentCustomer.Id) { return(Content("This is not your order")); } } var download = await _downloadService.GetDownloadById(product.DownloadId); if (download == null) { return(Content("Download is not available any more.")); } if (product.HasUserAgreement) { if (!agree) { return(RedirectToRoute("DownloadUserAgreement", new { orderItemId = orderItemId })); } } if (!product.UnlimitedDownloads && orderItem.DownloadCount >= product.MaxNumberOfDownloads) { return(Content(string.Format(_localizationService.GetResource("DownloadableProducts.ReachedMaximumNumber"), product.MaxNumberOfDownloads))); } if (download.UseDownloadUrl) { //increase download order.OrderItems.FirstOrDefault(x => x.Id == orderItem.Id).DownloadCount++; await _orderService.UpdateOrder(order); //return result return(new RedirectResult(download.DownloadUrl)); } //binary download if (download.DownloadBinary == null) { return(Content("Download data is not available any more.")); } //increase download order.OrderItems.FirstOrDefault(x => x.Id == orderItem.Id).DownloadCount++; await _orderService.UpdateOrder(order); if (product.ProductType != ProductType.BundledProduct) { //return result string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString(); string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : "application/octet-stream"; return(new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension }); } else { using (var memoryStream = new MemoryStream()) { using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { string fileName = (!String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString()) + download.Extension; if (Grand.Core.OperatingSystem.IsWindows()) { System.IO.File.WriteAllBytes(@"App_Data\Download\" + fileName, download.DownloadBinary); ziparchive.CreateEntryFromFile(@"App_Data\Download\" + fileName, fileName); } else { System.IO.File.WriteAllBytes(@"App_Data/Download/" + fileName, download.DownloadBinary); ziparchive.CreateEntryFromFile(@"App_Data/Download/" + fileName, fileName); } foreach (var bundle in product.BundleProducts) { var p1 = await _productService.GetProductById(bundle.ProductId); if (p1 != null && p1.IsDownload) { var d1 = await _downloadService.GetDownloadById(p1.DownloadId); if (d1 != null && !d1.UseDownloadUrl) { fileName = (!String.IsNullOrWhiteSpace(d1.Filename) ? d1.Filename : p1.Id.ToString()) + d1.Extension; if (Grand.Core.OperatingSystem.IsWindows()) { System.IO.File.WriteAllBytes(@"App_Data\Download\" + fileName, d1.DownloadBinary); ziparchive.CreateEntryFromFile(@"App_Data\Download\" + fileName, fileName); } else { System.IO.File.WriteAllBytes(@"App_Data/Download/" + fileName, d1.DownloadBinary); ziparchive.CreateEntryFromFile(@"App_Data/Download/" + fileName, fileName); } } } } } return(File(memoryStream.ToArray(), "application/zip", $"{Regex.Replace(product.Name, "[^A-Za-z0-9 _]", "")}.zip")); } } }
/// <summary> /// Inserts a file into the application bundle. /// </summary> /// <param name="filePath">The file to insert into the application bundle.</param> /// <param name="pathInArchive">The relative path of the file inside the application bundle.</param> public void InsertFileIntoXap(string filePath, string pathInArchive) { // Do not use "using" for the FileStream. The ZipArchive will close/dispose the stream unless // we specify otherwise. FileStream appArchiveFileStream = new FileStream(this.ArchiveFilePath, FileMode.Open, FileAccess.ReadWrite); using (ZipArchive zipArchive = new ZipArchive(appArchiveFileStream, ZipArchiveMode.Update)) { ZipArchiveEntry iconFileEntry = zipArchive.CreateEntry(pathInArchive, CompressionLevel.Fastest); using (Stream iconFileStream = iconFileEntry.Open()) { if (iconFileStream == null) { throw new ConsoleDriverException("Could not get file stream for icon from application archive."); } using (FileStream inputFileStream = new FileStream(filePath, FileMode.Open)) { inputFileStream.CopyTo(iconFileStream); } } } }
private void Generate_Click(object sender, RoutedEventArgs e) { this.Data.prevalidation = new List <Models.Error.Prevalidation>(); this.Data.subjects = new List <Models.Error.Subject>(); this.Data.contracts = new List <Models.Error.Contract>(); this.Data.prevalidationdetails = new List <Models.Error.PrevalidationDetails>(); this.Data.subjectdetails = new List <Models.Error.SubjectDetails>(); this.Data.contractdetails = new List <Models.Error.ContractDetails>(); this.Data.subjectdetailsData = new List <Models.Error.SubjectRows>(); preTab.IsEnabled = false; preGrid.IsEnabled = false; subTab.IsEnabled = false; subGrid.IsEnabled = false; preTab.IsEnabled = false; subTab.IsEnabled = false; tabControl.SelectedIndex = 0; using (var zipStream = new FileStream(ErrorFilePath, FileMode.Open)) { using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { foreach (var entry in archive.Entries) { //Console.WriteLine(entry.FullName); using (var stream = entry.Open()) { using (var reader = new StreamReader(stream)) { String line = ""; if (entry.FullName.Contains("ERROR_SUMMARY_PRE")) { int linenumber = 0; while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (linenumber > 0) { String[] LineData = line.Split('|'); Models.Error.Prevalidation p = new Models.Error.Prevalidation(); p.ErrorType = Convert.ToInt32(LineData[1]); p.ErrorCode = Convert.ToInt32(LineData[2]); p.ErrorCount = Convert.ToInt32(LineData[3]); p.ErrorDescription = LineData[4]; this.Data.prevalidation.Add(p); } linenumber++; } prevalidationSummaryData.Items.Refresh(); } if (entry.FullName.Contains("ERROR_PRE")) { int linenumber = 0; while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (linenumber > 0) { String[] LineData = line.Split('|'); Models.Error.PrevalidationDetails p = new Models.Error.PrevalidationDetails(); p.ProviderCode = LineData[1]; p.ReferrenceDate = LineData[2]; p.ErrorType = Convert.ToInt32(LineData[6]); p.ErrorCode = Convert.ToInt32(LineData[7]); p.RowNumber = Convert.ToInt32(LineData[9]); this.Data.prevalidationdetails.Add(p); } linenumber++; } } else if (entry.FullName.Contains("_ERROR_SUMMARY_LPS")) { int linenumber = 0; while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (linenumber > 0) { String[] LineData = line.Split('|'); Models.Error.Subject s = new Models.Error.Subject(); s.ErrorType = Convert.ToInt32(LineData[1]); s.ErrorCode = Convert.ToInt32(LineData[2]); s.ErrorCount = Convert.ToInt32(LineData[3]); s.ErrorDescription = LineData[4]; this.Data.subjects.Add(s); } linenumber++; } subjectnSummaryData.Items.Refresh(); } else if (entry.FullName.Contains("_ERROR_LPS")) { int linenumber = 0; while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (linenumber > 0) { String[] LineData = line.Split('|'); Models.Error.SubjectDetails s = new Models.Error.SubjectDetails(); s.ProviderCode = LineData[1]; s.ReferrenceDate = LineData[2]; s.SubjectCode = LineData[3]; s.ErrorType = Convert.ToInt32(LineData[6]); s.ErrorCode = Convert.ToInt32(LineData[7]); this.Data.subjectdetails.Add(s); } linenumber++; } } else if (entry.FullName.Contains("_ERROR_SUMMARY_LPC")) { int linenumber = 0; while ((line = reader.ReadLine()) != null) { //Console.WriteLine(line); if (linenumber > 0) { String[] LineData = line.Split('|'); Models.Error.Contract c = new Models.Error.Contract(); c.ProviderCode = LineData[0]; c.ErrorType = Convert.ToInt32(LineData[1]); c.ErrorCode = Convert.ToInt32(LineData[2]); c.ErrorCount = Convert.ToInt32(LineData[3]); c.ErrorDescription = LineData[4]; this.Data.contracts.Add(c); } linenumber++; } contractDetailData.Items.Refresh(); } else if (entry.FullName.Contains("_ERROR_LPC")) { int linenumber = 0; while ((line = reader.ReadLine()) != null) { if (linenumber > 0) { String[] LineData = line.Split('|'); Models.Error.ContractDetails c = new Models.Error.ContractDetails(); c.RecordType = LineData[0]; c.ProviderCode = LineData[1]; c.ReferrenceDate = LineData[2]; c.SubjectCode = LineData[3]; c.ContractCode = LineData[5]; c.ErrorType = Convert.ToInt32(LineData[6]); c.ErrorCode = Convert.ToInt32(LineData[7]); this.Data.contractdetails.Add(c); } linenumber++; } } } } } if (this.Data.prevalidation.Count > 0) { preTab.IsEnabled = true; preGrid.IsEnabled = true; } else { if (this.Data.contracts.Count > 0) { conTab.IsEnabled = true; conGrid.IsEnabled = true; tabControl.SelectedIndex = 2; } if (this.Data.subjects.Count > 0) { subTab.IsEnabled = true; subGrid.IsEnabled = true; tabControl.SelectedIndex = 1; } } } } //FILE READ AREA const Int32 BufferSize = 128; using (var fileStream = File.OpenRead(excelFile.Text)) { using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize)) { if (this.Data.prevalidation.Count > 0) { int LineNumber = 0; String line; while ((line = streamReader.ReadLine()) != null) { LineNumber++; if (this.Data.prevalidationdetails.FindIndex(o => o.RowNumber == LineNumber) >= 0) { //Models.Error.PrevalidationRows pf = new Models.Error.PrevalidationRows(); this.Data.prevalidationdetails.Find(o => o.RowNumber == LineNumber).ErrorData = line; //String[] columns = line.Split('|'); //pf.ErrorCode = Convert.ToInt32(columns[7]); //pf.ErrorType = Convert.ToInt32(columns[6]); //pf.RowNumber = LineNumber; //this.Data.prevalidationdetailsData.Add(pf); } } } else { int LineNumber = 0; String line; while ((line = streamReader.ReadLine()) != null) { String[] columns = line.Split('|'); if (columns[0] == "ID") { int i = this.Data.subjectdetails.FindIndex(o => o.SubjectCode == columns[4]); if (i >= 0) { this.Data.subjectdetails.Find(o => o.SubjectCode == columns[4]).ErrorData = line; this.Data.subjectdetails.Find(o => o.SubjectCode == columns[4]).RowNumber = (LineNumber + 1); } } if (columns[0] == "CI") { int i = this.Data.contractdetails.FindIndex(o => o.ContractCode == columns[6]); if (i >= 0) { this.Data.contractdetails.Find(o => o.ContractCode == columns[6]).ErrorData = line; this.Data.contractdetails.Find(o => o.ContractCode == columns[6]).RowNumber = (LineNumber + 1); } } LineNumber++; } // Process line } } } }
private static async Task UpdateArchive(ZipArchive archive, string installFile, string entryName) { string fileName = installFile; ZipArchiveEntry e = archive.CreateEntry(entryName); var file = FileData.GetFile(fileName); e.LastWriteTime = file.LastModifiedDate; using (var stream = await StreamHelpers.CreateTempCopyStream(fileName)) { using (Stream es = e.Open()) { es.SetLength(0); stream.CopyTo(es); } } }
public static void WriteCertificateAsPem(string name, byte[] rawBytes, string exportPassword, ZipArchive archive) { var a = new Pkcs12Store(); a.Load(new MemoryStream(rawBytes), Array.Empty <char>()); X509CertificateEntry entry = null; AsymmetricKeyEntry key = null; foreach (var alias in a.Aliases) { var aliasKey = a.GetKey(alias.ToString()); if (aliasKey != null) { entry = a.GetCertificate(alias.ToString()); key = aliasKey; break; } } if (entry == null) { throw new InvalidOperationException("Could not find private key."); } var zipEntryCrt = archive.CreateEntry(name + ".crt"); zipEntryCrt.ExternalAttributes = ((int)(FilePermissions.S_IRUSR | FilePermissions.S_IWUSR)) << 16; using (var stream = zipEntryCrt.Open()) using (var writer = new StreamWriter(stream)) { var pw = new PemWriter(writer); pw.WriteObject(entry.Certificate); } var zipEntryKey = archive.CreateEntry(name + ".key"); zipEntryKey.ExternalAttributes = ((int)(FilePermissions.S_IRUSR | FilePermissions.S_IWUSR)) << 16; using (var stream = zipEntryKey.Open()) using (var writer = new StreamWriter(stream)) { var pw = new PemWriter(writer); object privateKey; if (exportPassword != null) { privateKey = new MiscPemGenerator( key.Key, "DES-EDE3-CBC", exportPassword.ToCharArray(), CertificateUtils.GetSeededSecureRandom()) .Generate(); } else { privateKey = key.Key; } pw.WriteObject(privateKey); writer.Flush(); } }
internal ZipArchiveEntry(int index, ZipArchive archive, SeekableZipFilePart part) : base(part) { this.Index = index; this.archive = archive; }
private XRefArchive(XRefArchiveMode mode, ZipArchive archive, List <string> entries) { _mode = mode; _archive = archive; _entries = entries; }
public byte[] Run( IEnumerable <string> promptCards, IEnumerable <string> answerCards, float cardWidthInInches, float cardHeightInInches, float bleedSizeInInches, float borderRadius, float borderPaddingInInches, float maxPromptTextFontSize, float maxAnswerTextFontSize, Color promptCardFrontBackgroundColor, Color promptCardFrontTextColor, Color answerCardFrontBackgroundColor, Color answerCardFrontTextColor) { var imageCreator = new ImageCreator( cardWidthInInches, cardHeightInInches, bleedSizeInInches, borderRadius, borderPaddingInInches, maxPromptTextFontSize, maxAnswerTextFontSize, promptCardFrontBackgroundColor, promptCardFrontTextColor, answerCardFrontBackgroundColor, answerCardFrontTextColor); var promptCardsToGenerate = promptCards .Select((card, index) => new CardToGenerate { Index = index, Card = card, CreateImage = imageCreator.CreatePromptCardFront, FilePrefix = "Prompt" }); var answerCardsToGenerate = answerCards .Select((card, index) => new CardToGenerate { Index = index, Card = card, CreateImage = imageCreator.CreateAnswerCardFront, FilePrefix = "Answer" }); var allCards = promptCardsToGenerate .Concat(answerCardsToGenerate) .ToList(); using (var memoryStream = new MemoryStream()) { using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { foreach (var card in allCards) { var fileName = $"{card.FilePrefix} Card {card.Index}.svg"; var entry = zipArchive.CreateEntry(fileName); var document = card.CreateImage(card.Card); using (var singleFileStream = new MemoryStream()) { document.Write(singleFileStream); using (var zipStream = entry.Open()) zipStream.Write(singleFileStream.ToArray()); } } } return(memoryStream.ToArray()); } }
//async public Task FileWriteAsync(string line) { // using(System.IO.StreamWriter w = Delimon.Win32.IO.File.AppendText($"{baseDir}lista_arquivos.txt")) { // await w.WriteAsync(line); // } //} private void create_List(object sender, RoutedEventArgs e) { if (System.IO.File.Exists($"{baseDir}lista_arquivos.txt")) { System.IO.File.Delete($"{baseDir}lista_arquivos.txt"); } progressBar.Value = 0; wordPages = 0; wordFiles = 0; pdfPages = 0; pdfFiles = 0; button.IsEnabled = false; button1.IsEnabled = false; //sb = new StringBuilder("Tamanho (bytes)\tCaminho\tArquivo\tExtensão"); //zip = new StringBuilder("Tamanho (bytes)\tCaminho\tArquivo\tExtensão"); //System.IO.File.WriteAllText(baseDir + @"lista_arquivos.txt", "Tamanho (bytes)\tCaminho\tArquivo\tExtensão"); lista.Add("Tamanho (bytes)\tCaminho\tArquivo\tExtensão"); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); CreateList(sPath); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); Console.WriteLine($"CreateList RunTime {elapsedTime}"); //System.Windows.Forms.MessageBox.Show(elapsedTime, "CreateList RunTime", MessageBoxButtons.OK, MessageBoxIcon.Information); textBlock2.Text = "Total de páginas (PDF e Word): " + String.Format("{0:n0}", pdfPages + wordPages); //System.IO.File.WriteAllText($"{baseDir}lista_arquivos.txt", sb.ToString()); System.IO.File.AppendAllLines($"{baseDir}lista_arquivos.txt", lista); lista.Clear(); lista.TrimExcess(); using (var zipToOpen = new System.IO.FileStream($"{baseDir}lista_arquivos.zip", System.IO.FileMode.Create)) { using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { archive.CreateEntryFromFile($"{baseDir}lista_arquivos.txt", "lista_arquivos.txt"); } } // using(var zipToOpen = new System.IO.FileStream($"{baseDir}lista_arquivos.zip", System.IO.FileMode.Create)) { // using(var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)) { // var listEntry = archive.CreateEntry("lista_arquivos.txt"); // using(var writer = new System.IO.StreamWriter(listEntry.Open())) { // writer.WriteLine(sb); // } // } //} //System.IO.File.WriteAllText(baseDir + @"lista_arquivos_zip.txt", zip.ToString()); button.IsEnabled = true; button1.IsEnabled = true; System.Windows.Forms.MessageBox.Show($"O arquivo 'lista_arquivos.zip' foi criado em{Environment.NewLine}{baseDir}", "Arquivos processados com sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information); //System.Windows.Forms.MessageBox.Show($"Há {pdfFiles} documentos PDF totalizando {pdfPages} página(s).\r\nHá {wordFiles} documentos Word totalizando {wordPages} página(s).", "Páginas", MessageBoxButtons.OK, MessageBoxIcon.Information); }