public void Save(string file_name) { ZipStorer result = ZipStorer.Create(file_name, ""); // Create the output filename Stream data; // This will be out stream gStream sst = null; foreach (gStream g in streams) // Loop all the streams in the template { string name = g.zfe.FilenameInZip; // This is the stream name if (name != "xl/sharedStrings.xml") // If this is not the shared strings stream { if (!sources.TryGetValue(name, out data)) { data = g.ReadAsMemory(); // Get data stream either from memory or from Sources } result.AddStream(ZipStorer.Compression.Deflate, name, data, DateTime.Now, ""); // Add to our ZIP file } else { sst = g; } } if (!sources.TryGetValue("xl/sharedStrings.xml", out data)) { data = sst.ReadAsMemory(); // Get data stream either from memory or from Sources } result.AddStream(ZipStorer.Compression.Deflate, "xl/sharedStrings.xml", data, DateTime.Now, ""); // Add to our ZIP file result.Close(); // Close the ZIP file }
// // Private methods // private void DirToZipStream( IStorageService storage, string dir, string filter, QueryBlobsFilterDelegate queryFilter, ZipStorer zipStorer) { IEnumerable <string> storageNames = storage.QueryStorage(dir, filter); if (queryFilter != null) { storageNames = storageNames. Where(name => { bool passed = true; queryFilter(name, ref passed); return(passed); }); } try { foreach (string fileName in storageNames.Select(storageName => Path.Combine(dir, storageName))) { using (Stream readStream = new MemoryStream(storage.ReadStorage(fileName))) { zipStorer.AddStream(m_compression, fileName, readStream, DateTime.Now); } } } catch (Exception ex) { Log.WriteException(ex); } }
public static void AddText(this ZipStorer self, ZipStorer.Compression _method, string _text, string _filenameInZip, DateTime _modTime, string _comment) { byte[] bytes = Encoding.UTF8.GetBytes(_text); MemoryStream stream = new MemoryStream(bytes); self.AddStream(_method, _filenameInZip, stream, _modTime, _comment); }
private static void SaveTile(StyleData styleData, ZipStorer zip, ref int id) { using (var bmp = new Bitmap(64, 64)) { var bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); var stride = bmData.Stride; var scan0 = bmData.Scan0; unsafe { var p = (byte *)(void *)scan0; var nOffset = stride - bmp.Width * 4; for (var y = 0; y < bmp.Height; ++y) { for (var x = 0; x < bmp.Width; ++x) { uint tileColor = styleData.TileData[(y + (id / 4) * 64) * 256 + (x + (id % 4) * 64)]; var palId = (styleData.PaletteIndexes[id] / 64) * 256 * 64 + (styleData.PaletteIndexes[id] % 64) + tileColor * 64; var paletteIndex = palId % 64; p[0] = styleData.Palettes[paletteIndex].Colors[tileColor].B; p[1] = styleData.Palettes[paletteIndex].Colors[tileColor].G; p[2] = styleData.Palettes[paletteIndex].Colors[tileColor].R; p[3] = tileColor > 0 ? (byte)255 : (byte)0; p += 4; } p += nOffset; } } bmp.UnlockBits(bmData); var memoryStream = new MemoryStream(); bmp.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; zip.AddStream(ZipStorer.Compression.Deflate, id + Globals.TextureImageFormat, memoryStream, styleData.OriginalDateTime, string.Empty); memoryStream.Close(); } }
//ファイルをzipファイルに書き込む private static void WriteFileToZip(ZipStorer zip, FileInfo file, string fileNameInZip, ZipStorer.Compression compression) { using (var m = new MemoryStream(File.ReadAllBytes(file.FullName))) //対象をファイルから読み出す { m.Position = 0; //先頭からコピー zip.AddStream(compression, fileNameInZip, m, DateTime.Now, String.Empty); //zipファイルに格納する } }
public static void WriteZipFile(string filenameZip, string internalFileName, string text, string comment) { MemoryStream csvBytes = new MemoryStream(Encoding.UTF8.GetBytes(text)); using (ZipStorer zip = ZipStorer.Create(filenameZip, "")) { zip.AddStream(ZipStorer.Compression.Deflate, internalFileName, csvBytes, DateTime.Now, comment); } }
public static void StoreSqlText(string text) { byte[] ba = Encoding.UTF8.GetBytes(text); MemoryStream ms1 = new MemoryStream(ba); MemoryStream ms2 = new MemoryStream(); ZipStorer zip = ZipStorer.Create(ms2, "MySQL Backup"); zip.AddStream(ZipStorer.Compression.Deflate, "Backup.sql", ms1, DateTime.Now, "MySQL Backup"); zip.Close(); StoreZipFile(ms2.ToArray()); }
public void createSampleFile() { using (var mem = new MemoryStream(buffer)) { File.Delete(sampleFile); using (ZipStorer zip = ZipStorer.Create(sampleFile)) { zip.AddStream(ZipStorer.Compression.Deflate, "Lorem.txt", mem, DateTime.Now); } } }
public static MemoryStream WriteZipFileToMemory(string internalFileName, string text, string comment) { MemoryStream csvBytes = new MemoryStream(Encoding.UTF8.GetBytes(text)); ZipStorer zip = ZipStorer.Create(csvBytes, ""); zip.AddStream(ZipStorer.Compression.Deflate, internalFileName, csvBytes, DateTime.Now, comment); var ms = new MemoryStream(); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); zip.ExtractFile(dir[0], ms); return(ms); }
private static void SaveDelta(StyleData styleData, int spriteId, uint palette, uint deltaId, ZipStorer zip, string fileName) { var offset = 0; foreach (var deltaIndex in styleData.DeltaIndexes) { if (deltaIndex.Sprite == spriteId) { var spriteEntry = styleData.SpriteEntries[spriteId]; if (deltaIndex.DeltaSize.Count > 0) { for (var i = 0; i < deltaId; i++) { offset += deltaIndex.DeltaSize[i]; } using (var bmp = new Bitmap(spriteEntry.Width, spriteEntry.Height)) { var pos = 0; var recordLen = 0; var deltaLen = offset + deltaIndex.DeltaSize[(int)deltaId]; while (offset < deltaLen) { pos = BitConverter.ToUInt16(styleData.DeltaData, offset) + pos + recordLen; var x = pos % 256; var y = pos / 256; offset += 2; recordLen = styleData.DeltaData[offset]; offset++; for (var i = 0; i < recordLen; i++) { var color = styleData.Palettes[palette].Colors[styleData.DeltaData[offset]]; var imagePosX = x + i; var imagePosY = y; bmp.SetPixel(imagePosX, imagePosY, Color.FromArgb(255, color.R, color.G, color.B)); offset++; } } var memoryStream = new MemoryStream(); bmp.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; zip.AddStream(ZipStorer.Compression.Deflate, fileName + Globals.TextureImageFormat, memoryStream, styleData.OriginalDateTime, string.Empty); memoryStream.Close(); } } } else { offset += deltaIndex.DeltaSize.Sum(); } } }
protected override void FlushCore() { // Ensure that all the data has been read out of the package // stream already. Otherwise we'll lose data when we recreate the zip foreach (ZipPackagePart part in Parts.Values) { part.GetStream(); } if (!PackageStream.CanSeek) { return; } // Empty the package stream PackageStream.Position = 0; PackageStream.SetLength(0); // Recreate the zip file using (ZipStorer archive = ZipStorer.Create(PackageStream, "", false)) { // Write all the part streams foreach (ZipPackagePart part in Parts.Values) { Stream partStream = part.GetStream(); partStream.Seek(0, SeekOrigin.Begin); archive.AddStream(ZipStorer.Compression.Deflate, part.Uri.ToString().Substring(1), partStream, DateTime.UtcNow, ""); } using (var ms = new MemoryStream()) { WriteContentType(ms); ms.Seek(0, SeekOrigin.Begin); archive.AddStream(ZipStorer.Compression.Deflate, ContentUri, ms, DateTime.UtcNow, ""); } } }
/// <summary> /// Creates the mimetype file /// </summary> private void CreateMimetype() { //According to the specification, the mimetype must be the first file in the package //and cannot be compressed. ZipArchieve class don't have the option to set the compression //mode, only the compression level. So, even if we set the compression level to NoCompression //the file will still have the compression mode set to deflate and additional bytes //will be added before the file content. Because of this we're using Jaime Olivares's ZipStorer //class, so we can create a truely uncompressed mimetype file using (ZipStorer zs = ZipStorer.Create(zipStream, "", true)) using (MemoryStream mt = new MemoryStream()) { StreamWriter sw = new StreamWriter(mt); sw.Write("application/epub+zip"); sw.Flush(); mt.Seek(0, SeekOrigin.Begin); zs.AddStream(ZipStorer.Compression.Store, "mimetype", mt, DateTime.Now, ""); } }
public void WriteObjectItem(Stream stream, Func <int, object> getItem) { DateTime zipTime = DateTime.Now; using (ZipStorer zipStorer = ZipStorer.Create(stream)) { object item; int i = 0; while ((item = getItem(i)) != null) { using (MemoryStream unzipStraem = new MemoryStream()) { base.WriteObject(unzipStraem, item); unzipStraem.Position = 0; zipStorer.AddStream(ZipStorer.Compression.Deflate, i.ToString(), unzipStraem, zipTime); } i++; } } }
public void Test_Common() { Assert.Throws(typeof(ArgumentNullException), () => { ZipStorer.Open("", FileAccess.Read); }); string fileName = TestStubs.GetTempFilePath("test.zip"); using (ZipStorer zip = ZipStorer.Create(fileName, "test")) { using (MemoryStream csvStream = new MemoryStream(Encoding.ASCII.GetBytes(TestStubs.CSVData))) { zip.AddStream(ZipStorer.Compression.Deflate, "csv_file.csv", csvStream, DateTime.Now, ""); } Assert.Throws(typeof(InvalidOperationException), () => { zip.ReadCentralDir(); }); ZipStorer xzip = null; Assert.Throws(typeof(ArgumentNullException), () => { xzip = ZipStorer.RemoveEntries(xzip, null); }); Assert.Throws(typeof(ArgumentNullException), () => { xzip = ZipStorer.RemoveEntries(xzip, null); }); } using (ZipStorer zip = ZipStorer.Open(fileName, FileAccess.Read)) { Assert.Throws(typeof(ArgumentNullException), () => { zip.FindFile(null); }); ZipStorer.ZipFileEntry entry = zip.FindFile("invalid"); Assert.IsNull(entry); entry = zip.FindFile("csv_file.csv"); Assert.IsNotNull(entry); using (MemoryStream csvStream = new MemoryStream()) { Assert.Throws(typeof(ArgumentNullException), () => { zip.ExtractStream(entry, null); }); zip.ExtractStream(entry, csvStream); csvStream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(csvStream, Encoding.ASCII)) { string text = reader.ReadToEnd(); Assert.AreEqual(TestStubs.CSVData, text); } } } }
//Epubにファイルを追加する(mimetypeを除く) private static void WriteEpubFilesToZip(ZipStorer zip, string srcDir) { var files = Directory.GetFiles(srcDir, "*", SearchOption.AllDirectories); //全ファイル var targetFiles = files.Where(e => Path.GetFileName(e).Equals("mimetype") != true) //mimetypeを除く .Select(e => new FileInfo(e)); foreach (var targetFile in targetFiles) { var ext = targetFile.Extension; var compression = new ZipStorer.Compression(); switch (ext) { case "jpg": //画像ファイルは圧縮しない(時間の無駄なので) case "JPEG": case "png": case "PNG": case "gif": case "GIF": compression = ZipStorer.Compression.Store; break; case "EPUB": case "epub": continue; //EPUBファイルは格納しない default: compression = ZipStorer.Compression.Deflate; //通常のファイルは圧縮する break; } //対象を書き込む using (var ms = new MemoryStream(File.ReadAllBytes(targetFile.FullName))) { ms.Position = 0; //ファイルの先頭からコピー var fileNameInZip = GetRelPath(targetFile.FullName, srcDir); //zip内でのファイル名 zip.AddStream(compression, fileNameInZip, ms, DateTime.Now, string.Empty); } } }
private static void SaveSpriteRemap(StyleData styleData, SpriteEntry spriteEntry, uint palette, ZipStorer zip, string fileName) { using (var bmp = new Bitmap(spriteEntry.Width, spriteEntry.Height)) { var baseX = (int)(spriteEntry.Ptr % 256); var baseY = (int)(spriteEntry.Ptr / 256); var bmData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); var stride = bmData.Stride; var scan0 = bmData.Scan0; unsafe { var p = (byte *)(void *)scan0; var nOffset = stride - bmp.Width * 4; for (var y = 0; y < bmp.Height; ++y) { for (var x = 0; x < bmp.Width; ++x) { uint spriteColor = styleData.SpriteData[(baseX + x) + (baseY + y) * 256]; //var palId = (palette / 64) * 256 * 64 + (palette % 64) + spriteColor * 64; p[0] = styleData.Palettes[palette].Colors[spriteColor].B; p[1] = styleData.Palettes[palette].Colors[spriteColor].G; p[2] = styleData.Palettes[palette].Colors[spriteColor].R; p[3] = spriteColor > 0 ? (byte)255 : (byte)0; p += 4; } p += nOffset; } } bmp.UnlockBits(bmData); var memoryStream = new MemoryStream(); bmp.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; zip.AddStream(ZipStorer.Compression.Deflate, fileName + Globals.TextureImageFormat, memoryStream, styleData.OriginalDateTime, string.Empty); memoryStream.Close(); } }
void bg_DoWork(object sender, DoWorkEventArgs e) { MapInfo info = (MapInfo)e.Argument; if (!info.Area.IsEmpty) { string bigImage = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + Path.DirectorySeparatorChar + "GMap at zoom " + info.Zoom + " - " + info.Type + "-" + DateTime.Now.Ticks + ".png"; if (!string.IsNullOrEmpty(textBoxSaveAs.Text)) { bigImage = Path.Combine(Path.GetDirectoryName(textBoxSaveAs.Text), Path.GetFileName(bigImage)); } var smallImage = Path.Combine(Path.GetDirectoryName(bigImage), "layer.png"); if (!string.IsNullOrEmpty(textBoxSaveAs.Text)) { smallImage = textBoxSaveAs.Text; } e.Result = bigImage; // current area GPoint topLeftPx = info.Type.Projection.FromLatLngToPixel(info.Area.LocationTopLeft, info.Zoom); GPoint rightButtomPx = info.Type.Projection.FromLatLngToPixel(info.Area.Bottom, info.Area.Right, info.Zoom); GPoint pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y); GMap.NET.GSize maxOfTiles = info.Type.Projection.GetTileMatrixMaxXY(info.Zoom); int shrinkLoop = 0; int padding = info.MakeWorldFile || info.MakeKmz ? 0 : 22; { using (Bitmap bmpDestination = new Bitmap((int)(pxDelta.X + padding * 2), (int)(pxDelta.Y + padding * 2))) { using (Graphics gfx = Graphics.FromImage(bmpDestination)) { gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; gfx.SmoothingMode = SmoothingMode.HighQuality; int i = 0; // get tiles & combine into one lock (tileArea) { foreach (var p in tileArea) { if (bg.CancellationPending) { e.Cancel = true; return; } int pc = (int)(((double)++i / tileArea.Count) * 100); bg.ReportProgress(pc, p); foreach (var tp in info.Type.Overlays) { Exception ex; GMapImage tile; // tile number inversion(BottomLeft -> TopLeft) for pergo maps if (tp.InvertedAxisY) { tile = GMaps.Instance.GetImageFrom(tp, new GPoint(p.X, maxOfTiles.Height - p.Y), info.Zoom, out ex) as GMapImage; } else // ok { tile = GMaps.Instance.GetImageFrom(tp, p, info.Zoom, out ex) as GMapImage; } if (tile != null) { using (tile) { long x = p.X * info.Type.Projection.TileSize.Width - topLeftPx.X + padding; long y = p.Y * info.Type.Projection.TileSize.Width - topLeftPx.Y + padding; { gfx.DrawImage(tile.Img, x, y, info.Type.Projection.TileSize.Width, info.Type.Projection.TileSize.Height); } } } } } } // draw routes { foreach (GMapRoute r in Main.routes.Routes) { if (r.IsVisible) { using (GraphicsPath rp = new GraphicsPath()) { for (int j = 0; j < r.Points.Count; j++) { var pr = r.Points[j]; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); GPoint p2 = px; if (j == 0) { rp.AddLine(p2.X, p2.Y, p2.X, p2.Y); } else { System.Drawing.PointF p = rp.GetLastPoint(); rp.AddLine(p.X, p.Y, p2.X, p2.Y); } } if (rp.PointCount > 0) { gfx.DrawPath(r.Stroke, rp); } } } } } // draw polygons { foreach (GMapPolygon r in Main.polygons.Polygons) { if (r.IsVisible) { using (GraphicsPath rp = new GraphicsPath()) { for (int j = 0; j < r.Points.Count; j++) { var pr = r.Points[j]; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); GPoint p2 = px; if (j == 0) { rp.AddLine(p2.X, p2.Y, p2.X, p2.Y); } else { System.Drawing.PointF p = rp.GetLastPoint(); rp.AddLine(p.X, p.Y, p2.X, p2.Y); } } if (rp.PointCount > 0) { rp.CloseFigure(); gfx.FillPath(r.Fill, rp); gfx.DrawPath(r.Stroke, rp); } } } } } // draw markers { foreach (GMapMarker r in Main.objects.Markers) { if (r.IsVisible) { var pr = r.Position; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); px.Offset(r.Offset.X, r.Offset.Y); gfx.ResetTransform(); gfx.TranslateTransform(-r.LocalPosition.X, -r.LocalPosition.Y); gfx.TranslateTransform((int)px.X, (int)px.Y); r.OnRender(gfx); } } // tooltips above foreach (GMapMarker m in Main.objects.Markers) { if (m.IsVisible && m.ToolTip != null && m.IsVisible) { if (!string.IsNullOrEmpty(m.ToolTipText)) { var pr = m.Position; GPoint px = info.Type.Projection.FromLatLngToPixel(pr.Lat, pr.Lng, info.Zoom); px.Offset(padding, padding); px.Offset(-topLeftPx.X, -topLeftPx.Y); px.Offset(m.Offset.X, m.Offset.Y); gfx.ResetTransform(); gfx.TranslateTransform(-m.LocalPosition.X, -m.LocalPosition.Y); gfx.TranslateTransform((int)px.X, (int)px.Y); m.ToolTip.OnRender(gfx); } } } gfx.ResetTransform(); } // draw info if (!info.MakeWorldFile) { System.Drawing.Rectangle rect = new System.Drawing.Rectangle(); { rect.Location = new System.Drawing.Point(padding, padding); rect.Size = new System.Drawing.Size((int)pxDelta.X, (int)pxDelta.Y); } using (Font f = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold)) { // draw bounds & coordinates using (Pen p = new Pen(Brushes.DimGray, 3)) { p.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot; gfx.DrawRectangle(p, rect); string topleft = info.Area.LocationTopLeft.ToString(); SizeF s = gfx.MeasureString(topleft, f); gfx.DrawString(topleft, f, p.Brush, rect.X + s.Height / 2, rect.Y + s.Height / 2); string rightBottom = new PointLatLng(info.Area.Bottom, info.Area.Right).ToString(); SizeF s2 = gfx.MeasureString(rightBottom, f); gfx.DrawString(rightBottom, f, p.Brush, rect.Right - s2.Width - s2.Height / 2, rect.Bottom - s2.Height - s2.Height / 2); } // draw scale using (Pen p = new Pen(Brushes.Blue, 1)) { double rez = info.Type.Projection.GetGroundResolution(info.Zoom, info.Area.Bottom); int px100 = (int)(100.0 / rez); // 100 meters int px1000 = (int)(1000.0 / rez); // 1km gfx.DrawRectangle(p, rect.X + 10, rect.Bottom - 20, px1000, 10); gfx.DrawRectangle(p, rect.X + 10, rect.Bottom - 20, px100, 10); string leftBottom = "scale: 100m | 1Km"; SizeF s = gfx.MeasureString(leftBottom, f); gfx.DrawString(leftBottom, f, p.Brush, rect.X + 10, rect.Bottom - s.Height - 20); } } } } ImageUtilities.SavePng(bigImage, bmpDestination); Image shrinkImage = null; try { shrinkImage = bmpDestination; long size; if (long.TryParse(textBoxSizeFile.Text, out size)) { var fileLength = new FileInfo(bigImage).Length; if (fileLength > 0 && (fileLength / 1024 / 1024) > size) { while (shrinkLoop <= 100) { shrinkLoop++; int nextWidth = shrinkImage.Width * 80 / 100; int nextHeight = shrinkImage.Height * 80 / 100; // Shrink image shrinkImage = Stuff.FixedSize(shrinkImage, nextWidth, nextHeight); ImageUtilities.SavePng(smallImage, shrinkImage); fileLength = new FileInfo(smallImage).Length; if (fileLength > 0 && (fileLength / 1024 / 1024) < size) { break; } } } else { ImageUtilities.SavePng(smallImage, shrinkImage); } } else { MessageBox.Show("Invalide size - no shrinking.", "GMap.NET - Demo.WindowsForms", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "GMap.NET - Demo.WindowsForms", MessageBoxButtons.OK, MessageBoxIcon.Warning); } finally { shrinkImage.Dispose(); } } } //The worldfile for the original image is: //0.000067897543 // the horizontal size of a pixel in coordinate units (longitude degrees in this case); //0.0000000 //0.0000000 //-0.0000554613012 // the comparable vertical pixel size in latitude degrees, negative because latitude decreases as you go from top to bottom in the image. //-111.743323868834 // longitude of the pixel in the upper-left-hand corner. //35.1254392635083 // latitude of the pixel in the upper-left-hand corner. // generate world file if (info.MakeWorldFile) { string wf = Path.ChangeExtension(bigImage, "pgw"); using (StreamWriter world = File.CreateText(wf)) { world.WriteLine("{0:0.000000000000}", (info.Area.WidthLng / pxDelta.X)); world.WriteLine("0.0000000"); world.WriteLine("0.0000000"); world.WriteLine("{0:0.000000000000}", (-info.Area.HeightLat / pxDelta.Y)); world.WriteLine("{0:0.000000000000}", info.Area.Left); world.WriteLine("{0:0.000000000000}", info.Area.Top); world.Close(); } wf = Path.ChangeExtension(smallImage, "pgw"); using (StreamWriter world = File.CreateText(wf)) { world.WriteLine("{0:0.000000000000}", (info.Area.WidthLng / pxDelta.X) * (shrinkLoop > 0 ? Math.Pow(1.25, shrinkLoop) : 1)); world.WriteLine("0.0000000"); world.WriteLine("0.0000000"); world.WriteLine("{0:0.000000000000}", (-info.Area.HeightLat / pxDelta.Y) * (shrinkLoop > 0 ? Math.Pow(1.25, shrinkLoop) : 1)); world.WriteLine("{0:0.000000000000}", info.Area.Left); world.WriteLine("{0:0.000000000000}", info.Area.Top); world.Close(); } } if (info.MakeKmz) { var kmzFile = Path.GetDirectoryName(bigImage) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(bigImage) + ".kmz"; e.Result = kmzFile; using (ZipStorer zip = ZipStorer.Create(kmzFile, "GMap.NET")) { zip.AddFile(ZipStorer.Compression.Store, bigImage, "files/map.jpg", "map"); using (var readme = new MemoryStream( Encoding.UTF8.GetBytes( string.Format(CultureInfo.InvariantCulture, @"<?xml version=""1.0"" encoding=""UTF-8""?> <kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom""> <GroundOverlay> <name>{8}</name> <LookAt> <longitude>{6}</longitude> <latitude>{7}</latitude> <altitude>0</altitude> <heading>0</heading> <tilt>0</tilt> <range>69327.55500845652</range> </LookAt> <color>91ffffff</color> <Icon> <href>files/map.jpg</href> </Icon> <gx:LatLonQuad> <coordinates> {0},{1},0 {2},{3},0 {4},{5},0 {6},{7},0 </coordinates> </gx:LatLonQuad> </GroundOverlay> </kml>", info.Area.Left, info.Area.Bottom, info.Area.Right, info.Area.Bottom, info.Area.Right, info.Area.Top, info.Area.Left, info.Area.Top, kmzFile)))) { zip.AddStream(ZipStorer.Compression.Store, "doc.kml", readme, DateTime.Now, "kml"); zip.Close(); } } } } }
void AggregateLogs(EventReport report) { foreach (KeyValuePair <String, String[]> kvP in files) { String modName = kvP.Key; String[] filePaths = kvP.Value; // Does the file already exist? String path = KSPUtil.ApplicationRootPath + "Logs/" + "Logs-" + modName + ".zip"; Directory.CreateDirectory(Path.GetDirectoryName(path)); if (File.Exists(path)) { File.Delete(path); } using (ZipStorer zip = ZipStorer.Create(path, "")) { for (Int32 i = 0; i < filePaths.Length; i++) { String fullPath = Path.Combine(KSPUtil.ApplicationRootPath, filePaths[i]); // Is it a file? if (File.Exists(fullPath)) { // Make a temporary copy to avoid IO errors File.Copy(fullPath, "tmpfile", true); using (FileStream stream = File.OpenRead("tmpfile")) { zip.AddStream(ZipStorer.Compression.Deflate, filePaths[i], stream, DateTime.Now, ""); } // Remove the tmpfile File.Delete("tmpfile"); } // Is it a directory? if (Directory.Exists(fullPath)) { foreach (String file in Directory.GetFiles(fullPath, "*", SearchOption.AllDirectories)) { String nameInFile = file.Substring(KSPUtil.ApplicationRootPath.Length); if (nameInFile.StartsWith("/") || nameInFile.StartsWith("\\")) { nameInFile = nameInFile.Substring(1); } // Make a temporary copy to avoid IO errors File.Copy(file, "tmpfile", true); using (FileStream stream = File.OpenRead("tmpfile")) { zip.AddStream(ZipStorer.Compression.Deflate, nameInFile, stream, DateTime.Now, ""); } // Remove the tmpfile File.Delete("tmpfile"); } } } } } // I don't know if both events might fire so clean the storage to be sure the other method doesn't run files.Clear(); }
private static byte[] SaveBookInternal(EpubBook book) { var ms = new MemoryStream(); using (ZipStorer gz = ZipStorer.Create(ms, "")) { // mimetype File Stream mimeType = new MemoryStream(); var mtString = "application/epub+zip"; mimeType.Write(Encoding.ASCII.GetBytes(mtString), 0, mtString.Length); mimeType.Position = 0; gz.AddStream(ZipStorer.Compression.Deflate, "mimetype", mimeType, DateTime.Now, ""); // OPF File with three Elements: METADATA, MANIFEST, SPINE // container Stream metaInf = GetContainerData(book.ContainerData); gz.AddStream(ZipStorer.Compression.Deflate, "META-INF/container.xml", metaInf, DateTime.Now, ""); // opf var opfPath = book.ContainerData.Rootfiles.First().FullPath; // <item id="ncxtoc" media-type="application/x-dtbncx+xml" href="toc.ncx"/> book.PackageData.Manifest.Items.Add(new ContentFile { Identifier = book.PackageData.Spine.Toc, Href = "toc.ncx", MediaType = "application/x-dtbncx+xml" }); Stream opfData = GetOpfData(book.PackageData); gz.AddStream(ZipStorer.Compression.Deflate, opfPath, opfData, DateTime.Now, ""); // ncx //List<NavPoint> navmaplist = new List<NavPoint>(); //for (int i = 0; i < book.PackageData.Manifest.Items.Count; i++) //{ // if (book.PackageData.Manifest.Items[i].MediaType == "application/xhtml+xml") // { // navmaplist.Add(new NavPoint { Identifier = book.PackageData.Manifest.Items[i].Identifier, PlayOrder = (i + 1), LabelText = System.Text.Encoding.UTF8.GetString(book.PackageData.Manifest.Items[i].Data), Content = book.PackageData.Manifest.Items[i].Href }); // } //} book.GetTableOfContent().HeadMetaData = new Head(); book.GetTableOfContent().NavMap = book.NavigationData.NavMap; book.GetTableOfContent().HeadMetaData.Identifier = "isbn:9780735656680";// Guid.NewGuid().ToString(); book.GetTableOfContent().HeadMetaData.Creator = book.PackageData.MetaData.Creator.ToString(); book.GetTableOfContent().HeadMetaData.Depth = 2; book.GetTableOfContent().HeadMetaData.TotalPageCount = 0; book.GetTableOfContent().HeadMetaData.MaxPageNumber = 0; Stream ncxData = GetNcxData(book.GetTableOfContent(), book.PackageData.MetaData.Title.Text); string ncxElement = Helper.CreatePath(Path.GetDirectoryName(opfPath), "toc.ncx"); gz.AddStream(ZipStorer.Compression.Deflate, ncxElement, ncxData, DateTime.Now, ""); // take manifest items and create remaining files var oepbsPath = Path.GetDirectoryName(opfPath); foreach (var item in book.GetAllFiles().Where(file => file.Href != "toc.ncx")) { var msItem = new MemoryStream(item.Data); msItem.Position = 0; var path = String.Format("{0}/{1}", oepbsPath, item.Href); gz.AddStream(ZipStorer.Compression.Deflate, path, msItem, DateTime.Now, ""); } ms.Position = 0; return(ms.ToArray()); } }
public void PushToZip(DeduplicatorState state, ZipStorer zip) { // All files that don't reside under protobuild/ have to be // maintained intact for NuGet to work properly. var rootCopies = new Dictionary <string, string>(); foreach (var kv in state.DestinationToFileHash) { if (kv.Key.ToLowerInvariant().Replace('\\', '/').StartsWith("protobuild/")) { // This file can be deduplicated. } else { // This file can not be deduplicated and must reside in place. We keep // a dictionary in memory that allows the file at it's currently location // to be the deduplication target for any files under protobuild/ that match, // instead of also storing a copy under _DedupFiles. if (kv.Value == null) { // Directory; ignore this since they are automatically recreated by the // reduplicator. continue; } rootCopies[kv.Value] = kv.Key; state.FileHashToSource[kv.Value].Seek(0, SeekOrigin.Begin); zip.AddStream( ZipStorer.Compression.Deflate, kv.Key, state.FileHashToSource[kv.Value], DateTime.UtcNow, string.Empty, true); } } // Now store any files that weren't stored in the package root, into a // _DedupFiles folder. foreach (var kv in state.FileHashToSource) { if (rootCopies.ContainsKey(kv.Key)) { // This was stored in the root of the package already. } else { // We need to store this under _DedupFiles. kv.Value.Seek(0, SeekOrigin.Begin); zip.AddStream( ZipStorer.Compression.Deflate, "_DedupFiles/" + kv.Key, kv.Value, DateTime.UtcNow, string.Empty, true); } } // Now write out the text file that has the mappings. While in a tar/gz // file we use symlinks, those aren't available for ZIP packages, so we // need a text file in the root of the package that describes path to path // mappings. using (var mappingStream = new MemoryStream()) { using (var writer = new StreamWriter(mappingStream, Encoding.UTF8, 4096, true)) { foreach (var kv in state.DestinationToFileHash) { if (kv.Value == null) { // Directory. writer.WriteLine(kv.Key + "?<DIRECTORY>"); continue; } if (rootCopies.ContainsKey(kv.Value)) { writer.WriteLine(kv.Key + "?" + rootCopies[kv.Value]); } else { writer.WriteLine(kv.Key + "?_DedupFiles/" + kv.Value); } } writer.Flush(); mappingStream.Seek(0, SeekOrigin.Begin); zip.AddStream( ZipStorer.Compression.Deflate, "_DedupIndex.txt", mappingStream, DateTime.UtcNow, "Deduplication Index Lookup"); } } }