/// <summary> /// zip压缩 /// </summary> /// <param name="paths">文件绝对路径</param> /// <param name="zipPath">zip文件绝对路径</param> /// <returns>是否压缩成功</returns> public static bool CreateZip(List <string> paths, string zipPath) { using (ZipStorer zip = ZipStorer.Create(zipPath, string.Empty)) { List <Tuple <string, string> > exPathWithRels = new List <Tuple <string, string> >(); //绝对路径 zip中的相对路径 foreach (string path in paths) { //参数中所有路径 if (File.Exists(path)) { //文件 zip.AddFile(ZipStorer.Compression.Deflate, path, Path.GetFileName(path), string.Empty); } else if (Directory.Exists(path)) { //文件夹 int pathLength = Path.GetDirectoryName(path).Length; //获取目录长度 List <string> exPaths = TPath.GetFilePaths(path); //获取文件夹中所有文件 包含子目录中文件 foreach (string exPath in exPaths) { exPathWithRels.Add(Tuple.Create(exPath, exPath.Remove(0, pathLength))); } } else { throw new InvalidOperationException("路径非法:" + path); } } foreach (var path in exPathWithRels) { if (File.Exists(path.Item1)) { //文件夹中文件路径 zip.AddFile(ZipStorer.Compression.Deflate, path.Item1, path.Item2, string.Empty); } else { throw new InvalidOperationException("路径非法:" + path); } } } return(true); }
static void DoBackup() { string backupFileName = String.Format(BackupFileNameFormat, DateTime.Now); // localized using (FileStream fs = File.Create(backupFileName)) { using (ZipStorer backupZip = ZipStorer.Create(fs, "")) { foreach (string dataFileName in FilesToBackup) { if (File.Exists(dataFileName)) { backupZip.AddFile(ZipStorer.Compression.Deflate, dataFileName, dataFileName, ""); } } } } }
private void AddMimetype(ZipStorer zip) { Helper.Debug("Adding mimetype"); // Make sure there is no UTF-8 BOM var encoding = new UTF8Encoding(false); var mimetype = encoding.GetBytes("application/epub+zip"); File.WriteAllBytes(CurrentDirectory + "mimetype", mimetype); // Add mimetype without compression zip.AddFile( ZipStorer.Compression.Store, CurrentDirectory + "mimetype", "mimetype" ); }
public static void PackedZip(string pathFolder, string zipName) { ZipStorer zip = ZipStorer.Create(zipName + ".zip", ""); zip.EncodeUTF8 = true; string path = pathFolder; string[] arrFiles = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); foreach (var item in arrFiles) { string newPath = item.Replace(path, ""); zip.AddFile(ZipStorer.Compression.Deflate, item, newPath, ""); } zip.Close(); }
public static bool RemoveEntries(ref ZipStorer _zip, List <ZipFileEntry> _zfes) { if (!(_zip.ZipFileStream is FileStream)) { throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream"); } List <ZipFileEntry> list = _zip.ReadCentralDir(); string tempFileName = Path.GetTempFileName(); string tempFileName2 = Path.GetTempFileName(); bool result; try { ZipStorer zipStorer = Create(tempFileName, string.Empty); foreach (ZipFileEntry current in list) { if (!_zfes.Contains(current) && _zip.ExtractFile(current, tempFileName2)) { zipStorer.AddFile(current.Method, tempFileName2, current.FilenameInZip, current.Comment); } } _zip.Close(); zipStorer.Close(); File.Delete(_zip.FileName); File.Move(tempFileName, _zip.FileName); _zip = Open(_zip.FileName, _zip.Access); } catch { result = false; return(result); } finally { if (File.Exists(tempFileName)) { File.Delete(tempFileName); } if (File.Exists(tempFileName2)) { File.Delete(tempFileName2); } } result = true; return(result); }
private static void Main() { FileInfo binaries = new FileInfo(BinariesFileName); if (binaries.Exists) { binaries.Delete(); } using (ZipStorer zs = ZipStorer.Create(binaries.FullName, "")) { foreach (string file in FileList) { FileInfo fi = new FileInfo(file); if (!fi.Exists) { return; // abort if any of the files do not exist } zs.AddFile(ZipStorer.Compression.Deflate, fi.FullName, fi.Name, ""); } } }
static void DoBackup() { if (!Directory.Exists(DataBackupDirectory)) { Directory.CreateDirectory(DataBackupDirectory); } string backupFileName = String.Format(BackupFileNameFormat, DateTime.Now); // localized backupFileName = Path.Combine(DataBackupDirectory, backupFileName); using (FileStream fs = File.Create(backupFileName)) { using (ZipStorer backupZip = ZipStorer.Create(fs, "")) { foreach (string dataFileName in FilesToBackup) { if (File.Exists(dataFileName)) { backupZip.AddFile(ZipStorer.Compression.Deflate, dataFileName, dataFileName, ""); } } } } }
public static Action <List <XMindWriterContext> > ZipXMindFolder(string xmindFileName) { var xMindSettings = XMindConfigurationCache.Configuration.XMindConfigCollection; var filesToZipLabels = new string[] { "output:definition:meta", "output:definition:manifest", "output:definition:content" }; var fileNames = filesToZipLabels.Select(label => xMindSettings[label]).ToList(); var filesToZip = xMindSettings.GetSection("output:files") .GetChildren().Where( x => fileNames .Contains( x.GetChildren() .Where(el => el.Key == "name").Select(el => el.Value).FirstOrDefault() ) ) .Select(x => (File: x["name"], Path: x["location"])) .ToList(); return(ctx => { using (ZipStorer zip = ZipStorer.Create(Path.Combine(xMindSettings["output:base"], xmindFileName), string.Empty)) { foreach (var fileToken in filesToZip) { var fullPath = Path.Combine( Environment.CurrentDirectory, XMindConfigurationCache.Configuration.XMindConfigCollection["output:base"], fileToken.Path, fileToken.File ); zip.AddFile(ZipStorer.Compression.Deflate, fullPath, fileToken.File, string.Empty); } // zip.AddFile(ZipStorer.Compression.Deflate, "META-INF\\manifest.xml", "manifest.xml", string.Empty); // zip.AddFile(ZipStorer.Compression.Deflate, "meta.xml", "meta.xml", string.Empty); // zip.AddFile(ZipStorer.Compression.Deflate, "content.xml", "content.xml", string.Empty); } }); }
public string ToBase64String() { string result = string.Empty; this.WriteToDisk(); using (MemoryStream memoryStream = new MemoryStream()) { using (ZipStorer zipStorer = ZipStorer.Create(memoryStream, string.Empty)) { string[] files = Directory.GetFiles(this.profileDir, "*.*", SearchOption.AllDirectories); string[] array = files; for (int i = 0; i < array.Length; i++) { string text = array[i]; string fileNameInZip = text.Substring(this.profileDir.Length).Replace(Path.DirectorySeparatorChar, '/'); zipStorer.AddFile(ZipStorer.CompressionMethod.Deflate, text, fileNameInZip, string.Empty); } } result = Convert.ToBase64String(memoryStream.ToArray()); this.Clean(); } return(result); }
private bool CreateZip(string zipFile, string source) { bool ret = false; ZipStorer storer = ZipStorer.Create(zipFile, ""); List <string> rawFiles = new List <string>(); GetFolderRecursive(source, ref rawFiles); try { rawFiles.ForEach( x => storer.AddFile(ZipStorer.Compression.Deflate, x, FilterInZip(txtFolderToSign.Text, x), "") ); storer.Close(); ret = true; } catch (Exception ex) { MessageBox.Show("Could not create ZIP File: " + ex.ToString(), "Zip Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(ret); }
/// <summary> /// Transfer a single file /// </summary> private bool DeploySingleFile(FileToDeploy file) { if (!file.IsOk) { if (File.Exists(file.From)) { switch (file.DeployType) { case DeployType.Copy: file.IsOk = Utils.CopyFile(file.From, file.To); break; case DeployType.Move: file.IsOk = Utils.MoveFile(file.From, file.To, true); break; case DeployType.Ftp: file.IsOk = Utils.SendFileToFtp(file.From, file.To); break; case DeployType.Zip: try { ZipStorer zip = _openedZip[file.ArchivePath]; zip.AddFile(ZipStorer.Compression.Deflate, file.From, file.RelativePathInArchive, "Added @ " + DateTime.Now); file.IsOk = true; } catch (Exception e) { ErrorHandler.ShowErrors(e, "Zipping during deployment"); file.IsOk = false; } break; } } return(true); } return(false); }
/// <summary> /// Converts the profile into a base64-encoded string. /// </summary> /// <returns>A base64-encoded string containing the contents of the profile.</returns> public string ToBase64String() { string base64zip = string.Empty; this.WriteToDisk(); using (MemoryStream profileMemoryStream = new MemoryStream()) { using (ZipStorer profileZipArchive = ZipStorer.Create(profileMemoryStream, string.Empty)) { string[] files = Directory.GetFiles(this.profileDir, "*.*", SearchOption.AllDirectories); foreach (string file in files) { string fileNameInZip = file.Substring(this.profileDir.Length).Replace(Path.DirectorySeparatorChar, '/'); profileZipArchive.AddFile(ZipStorer.CompressionMethod.Deflate, file, fileNameInZip, string.Empty); } } base64zip = Convert.ToBase64String(profileMemoryStream.ToArray()); this.Clean(); } return(base64zip); }
public void ZipUnzipTextFile() { string zipFileComment = "This is a test comment."; string fileComment = "This is a file comment."; string[] myFile = new string[10000]; for (int i = 0; i < myFile.Length; i++) { myFile[i] = "My file contains a new line, namely line : " + i; } File.WriteAllLines("tmp.txt", myFile); var filesizeOfInput = new FileInfo("tmp.txt").Length; ZipStorer writeZipFile = ZipStorer.Create("ziptmp2.zip", zipFileComment); writeZipFile.AddFile(ZipStorer.Compression.Deflate, "tmp.txt", "tmp.txt", fileComment); writeZipFile.AddFile(ZipStorer.Compression.Deflate, "tmp.txt", "tmp2.txt", fileComment); writeZipFile.Close(); ZipStorer readZipFile = ZipStorer.Open("ziptmp2.zip", FileAccess.Read); Assert.AreEqual(zipFileComment, readZipFile.Comment); var files = readZipFile.ReadCentralDir(); Assert.AreEqual(2, files.Count); Assert.AreEqual("tmp.txt", files[0].FilenameInZip); Assert.AreEqual("tmp2.txt", files[1].FilenameInZip); Assert.AreEqual(filesizeOfInput, files[0].FileSize); Assert.AreEqual(filesizeOfInput, files[1].FileSize); Assert.LessOrEqual(files[0].CompressedSize, filesizeOfInput); Assert.LessOrEqual(files[1].CompressedSize, filesizeOfInput); Debug.WriteLine("Compression ratio: " + Math.Round(files[0].CompressedSize * 100.0 / filesizeOfInput, 3) + "%"); readZipFile.ExtractFile(files[0], "./tmpout.txt"); readZipFile.ExtractFile(files[0], "./tmp2out.txt"); string[] file1 = File.ReadAllLines("./tmpout.txt"); string[] file2 = File.ReadAllLines("./tmp2out.txt"); Assert.AreEqual(myFile.Length, file1.Length); Assert.AreEqual(myFile.Length, file2.Length); for (int i = 0; i < myFile.Length; i++) { Assert.AreEqual(myFile[i], file1[i]); Assert.AreEqual(myFile[i], file2[i]); } // All is well! readZipFile.Close(); readZipFile = null; writeZipFile = null; File.Delete("tmp.txt"); File.Delete("ziptmp2.zip"); File.Delete("tmpout.txt"); File.Delete("tmp2out.txt"); }
private void AddFile(ZipStorer zipStorer, string includePath, string filename, string relativePath, int indent) { zipStorer.AddFile(ZipStorer.Compression.Deflate, includePath, (!string.IsNullOrEmpty(relativePath) ? string.Format("{0}\\{1}", relativePath, filename) : filename), string.Empty); WriteLineConsole(string.Format("{0}Added : {1}", new string(' ', indent * 2), filename)); }
private void btnFromDb_Click(object sender, EventArgs e) { using (FolderBrowserDialog dlg = new FolderBrowserDialog()) { dlg.Description = "مسیر خروجیها را انتخاب کنید"; dlg.ShowNewFolderButton = true; if (dlg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { bool embedPictures = false; string picPath = string.Empty; string picUrPrefix = string.Empty; using (GDBPictureDirSelector plg = new GDBPictureDirSelector()) if (plg.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { embedPictures = plg.EmbedPictures; picPath = plg.PicturesPath; picUrPrefix = plg.PicturesUrlPrefix; if (!Directory.Exists(picPath)) { embedPictures = false; } } this.Enabled = false; List <int> existingIDs = new List <int>(); foreach (DataGridViewRow Row in grd.Rows) { if (!Row.IsNewRow) { bool err = false; GDBInfo gdb = ConvertGridRowToGDBInfo(Row, ref err); if (!err) { existingIDs.Add(gdb.PoetID); } } } DbBrowser db = new DbBrowser(); foreach (GanjoorPoet Poet in db.Poets) { if (existingIDs.IndexOf(Poet._ID) == -1)//existing items in grid { string outFile = Path.Combine(dlg.SelectedPath, GPersianTextSync.Farglisize(Poet._Name)); string gdbFile = outFile + ".gdb"; if (db.ExportPoet(gdbFile, Poet._ID)) { string zipFile = outFile + ".zip"; using (ZipStorer zipStorer = ZipStorer.Create(zipFile, "")) { zipStorer.AddFile(ZipStorer.Compression.Deflate, gdbFile, Path.GetFileName(gdbFile), ""); if (embedPictures) { string pngPath = Path.Combine(picPath, Poet._ID.ToString() + ".png"); if (File.Exists(pngPath)) { zipStorer.AddFile(ZipStorer.Compression.Deflate, pngPath, Path.GetFileName(pngPath), ""); } } } File.Delete(gdbFile); int RowIndex = AddGdbOrZipFileToGrid(zipFile); if (embedPictures && !string.IsNullOrEmpty(picUrPrefix)) { string pngPath = Path.Combine(picPath, Poet._ID.ToString() + ".png"); if (File.Exists(pngPath)) { grd.Rows[RowIndex].Cells[CLMN_IMAGE].Value = picUrPrefix + Path.GetFileName(pngPath); } } Application.DoEvents(); } else { MessageBox.Show(db.LastError); } } } this.Enabled = true; db.CloseDb(); } } }
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(); } } } } }
public void ExportData(string path, string zipname, string _cdbfile, string modulescript) { int i = 0; Card[] cards = this.cardlist; if (cards == null || cards.Length == 0) { return; } int count = cards.Length; YgoPath ygopath = new YgoPath(path); string name = Path.GetFileNameWithoutExtension(zipname); //数据库 string cdbfile = zipname + ".cdb"; //说明 string readme = MyPath.Combine(path, name + ".txt"); //新卡ydk string deckydk = ygopath.GetYdk(name); //module scripts string extra_script = ""; if (modulescript.Length > 0) { extra_script = ygopath.GetModuleScript(modulescript); } File.Delete(cdbfile); DataBase.Create(cdbfile); DataBase.CopyDB(cdbfile, false, this.cardlist); if (File.Exists(zipname)) { File.Delete(zipname); } using (ZipStorer zips = ZipStorer.Create(zipname, "")) { zips.AddFile(cdbfile, Path.GetFileNameWithoutExtension(_cdbfile) + ".cdb", ""); if (File.Exists(readme)) { zips.AddFile(readme, "readme_" + name + ".txt", ""); } if (File.Exists(deckydk)) { zips.AddFile(deckydk, "deck/" + name + ".ydk", ""); } if (modulescript.Length > 0 && File.Exists(extra_script)) { zips.AddFile(extra_script, extra_script.Replace(path, ""), ""); } foreach (Card c in cards) { i++; this.worker.ReportProgress(i / count, string.Format("{0}/{1}", i, count)); string[] files = ygopath.GetCardfiles(c.id); foreach (string file in files) { if (!string.Equals(file, extra_script) && File.Exists(file)) { zips.AddFile(file, file.Replace(path, ""), ""); } } } } File.Delete(cdbfile); }
public void ZipUnzipBinaryFile() { string zipFileComment = "This is a test comment."; string fileComment = "This is a file comment."; byte[] myFile = new byte[1024 * 1024]; Random rand = new Random(102019123); for (int i = 0; i < myFile.Length; i++) { myFile[i] = (byte)(rand.Next(1, 256)); } File.WriteAllBytes("tmp.bin", myFile); var filesizeOfInput = new FileInfo("tmp.bin").Length; ZipStorer writeZipFile = ZipStorer.Create("ziptmp.zip", zipFileComment); writeZipFile.AddFile(ZipStorer.Compression.Deflate, "tmp.bin", "tmp.bin", fileComment); writeZipFile.AddFile(ZipStorer.Compression.Deflate, "tmp.bin", "tmp2.bin", fileComment); writeZipFile.Close(); ZipStorer readZipFile = ZipStorer.Open("ziptmp.zip", FileAccess.Read); Assert.AreEqual(zipFileComment, readZipFile.Comment); var files = readZipFile.ReadCentralDir(); Assert.AreEqual(2, files.Count); Assert.AreEqual("tmp.bin", files[0].FilenameInZip); Assert.AreEqual("tmp2.bin", files[1].FilenameInZip); Assert.AreEqual(filesizeOfInput, files[0].FileSize); Assert.AreEqual(filesizeOfInput, files[1].FileSize); Assert.LessOrEqual(files[0].CompressedSize, filesizeOfInput); Assert.LessOrEqual(files[1].CompressedSize, filesizeOfInput); var compressionRate = files[0].CompressedSize * 100.0 / filesizeOfInput; Assert.AreEqual(100.0, compressionRate, 0.1); // we use completely random data, so it's a very bad compression ratio Debug.WriteLine("Compression ratio: " + compressionRate + "%"); readZipFile.ExtractFile(files[0], "./tmpout.bin"); readZipFile.ExtractFile(files[0], "./tmp2out.bin"); byte[] file1 = File.ReadAllBytes("./tmpout.bin"); byte[] file2 = File.ReadAllBytes("./tmp2out.bin"); Assert.AreEqual(myFile.Length, file1.Length); Assert.AreEqual(myFile.Length, file2.Length); for (int i = 0; i < myFile.Length; i++) { Assert.AreEqual(myFile[i], file1[i]); Assert.AreEqual(myFile[i], file2[i]); } // All is well! readZipFile.Close(); readZipFile = null; writeZipFile = null; File.Delete("tmp.txt"); File.Delete("tmp.bin"); File.Delete("tmpout.bin"); File.Delete("tmp2out.bin"); File.Delete("ziptmp.zip"); File.Delete("tmpout.txt"); File.Delete("tmp2out.txt"); }
//kernel of protocol Client side private static void FTP_protocol(string ip, string port, string firstNameReceiver, string lastnameReceiver) { Console.WriteLine("[Client] - Inizio invio a " + ip + ":" + port + " nome: " + firstNameReceiver + " cognome: " + lastnameReceiver); byte[] buffer = new byte[1024]; string msg = ""; string msg_progress = ""; byte[] buffer2 = new byte[1024]; TcpClient client = new TcpClient(); BinaryWriter writer = null; BinaryReader reader = null; string zipDir = null; SendFile windowSendFile = null; ZipStorer zipFile = null; string zipFileName = null; if (!Directory.Exists(LANSharingApp.tmpPath)) { Directory.CreateDirectory(LANSharingApp.tmpPath); } try { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)); string type = null; Console.WriteLine("[Client] - tentativo invio a:" + ip + ":" + port + " nome: " + firstNameReceiver + " cognome: " + lastnameReceiver); client.ReceiveBufferSize = 1024; client.SendBufferSize = 1024; Console.WriteLine("[Client] - creato tcp client"); //start connection TCP client.Connect(IPAddress.Parse(ip), int.Parse(port)); Console.WriteLine("[Client] - connesso tcp client"); using (NetworkStream networkStream = client.GetStream()) { writer = new BinaryWriter(networkStream); reader = new BinaryReader(networkStream); // send header to the Server // userFirstName,userLastName, userIP @ type @ path string userFirstName = LANSharingApp.umu.getAdmin().getFirstName(); string userLastName = LANSharingApp.umu.getAdmin().getLastName(); string userIp = LANSharingApp.umu.getAdmin().getIp().ToString(); string myPath = null; string fullPath = null; lock (LANSharingApp.lockerPathSend) { myPath = Path.GetFileName(LANSharingApp.pathSend); fullPath = LANSharingApp.pathSend; } //identify if the admin is sending a file or a directory if ((File.GetAttributes(fullPath) & FileAttributes.Directory) == FileAttributes.Directory) { type = "directory"; } else { type = "file"; } // case file if (type.CompareTo("file") == 0) { // username,usersurname, userip @ type @ path @ checkNumber //msg_progress = nameReceiver + "," + lastnameReceiver + "," + ip + "@" + type + "@" + myPath + "@" + dataToSend.Length; msg = userFirstName + "," + userLastName + "," + userIp + "@" + type + "@" + myPath; writer.Write(msg); Console.WriteLine("[Client] - Inviato al server: " + msg); Console.WriteLine("[Client] - aspetto risposta"); //wait for answer msg = reader.ReadString(); Console.WriteLine("[Client] - risposta ricevuta: " + msg); if (msg.CompareTo("ok") == 0) { //if ok, send file //check file if (!File.Exists(fullPath)) { MessageFormError mfe = new MessageFormError("Error: file deleted"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); return; } Console.WriteLine("[Client] - inizio invio file "); //zip the file string randomName = LANSharingApp.tmpPath + "\\" + Path.GetRandomFileName(); //add file to list LANSharingApp.tempFileSend.Add(randomName); //specific progress bar for each different user windowSendFile = new SendFile("Progress of ftp file " + myPath + " to " + firstNameReceiver + " " + lastnameReceiver, "Compression in Progress"); windowSendFile.StartPosition = FormStartPosition.CenterScreen; int offset = 0; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Show(); } }); zipFileName = randomName; zipFile = ZipStorer.Create(randomName, ""); zipFile.AddFile(ZipStorer.Compression.Store, fullPath, Path.GetFileName(myPath), ""); zipFile.Close(); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.clearCompression(); } }); //some usefull information byte[] dataToSend = File.ReadAllBytes(randomName); msg = dataToSend.Length + ""; writer.Write(msg); int chunk = 1024 * 1024; int n = dataToSend.Length / chunk; int lastChunk = dataToSend.Length - (n * chunk); int i; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.setMinMaxBar(0, n + 1); } }); for (i = 0; i < n; i++) { if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } else { // no cancel networkStream.Write(dataToSend, offset, chunk); networkStream.Flush(); offset += chunk; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); } } Thread.Sleep(5000); // give time to user to react if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } if (lastChunk != 0) { networkStream.Write(dataToSend, offset, lastChunk); networkStream.Flush(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); Console.WriteLine("[Client] - fine invio file "); Console.WriteLine("[Client] - close protocol "); } else//cancel { Console.WriteLine("[Client] - close protocol "); MessageFormError mfex = new MessageFormError(firstNameReceiver + " " + lastnameReceiver + " refused file"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfex.Show(); }); } Thread.Sleep(1000); // give time to sender to see the final state of progress bar // delegate the operation on form to the GUI --> close the send window if (windowSendFile != null) { LANSharingApp.gui.Invoke((MethodInvoker) delegate() { windowSendFile.Close(); }); } } else //case directory { // username,usersurname, userip @ type @ path msg = userFirstName + "," + userLastName + "," + userIp + "@" + type + "@" + myPath; writer.Write(msg); Console.WriteLine("[Client] - Inviato al server: " + msg); Console.WriteLine("[Client] - aspetto risposta"); //wait answer msg = reader.ReadString(); Console.WriteLine("[Client] - risposta ricevuta: " + msg); if (msg.CompareTo("ok") == 0) { // if ok, send directory if (!Directory.Exists(fullPath)) { MessageFormError mfe = new MessageFormError("Error: directory deleted during send process"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); }); return; } //zip directory, better performance on LAN //random name, no collision on creation multiple zip of same file zipDir = LANSharingApp.tmpPath + "\\" + Path.GetRandomFileName(); //add to list LANSharingApp.tempFileSend.Add(zipDir); //specific progress bar for each different user windowSendFile = new SendFile("Progress of ftp directory " + myPath + " to " + firstNameReceiver + " " + lastnameReceiver, " Compression in progress"); windowSendFile.StartPosition = FormStartPosition.CenterScreen; int offset = 0; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Show(); } }); ZipFile.CreateFromDirectory(fullPath, zipDir, CompressionLevel.NoCompression, true); Console.WriteLine("[Client] - zip creato:" + zipDir); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.clearCompression(); } }); Console.WriteLine("[Client] - inizio invio directory zip"); byte[] dataToSend = File.ReadAllBytes(zipDir); msg = dataToSend.Length + ""; writer.Write(msg); int chunk = 1024 * 1024; int n = dataToSend.Length / chunk; int lastChunk = dataToSend.Length - (n * chunk); int i; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.setMinMaxBar(0, n + 1); } }); for (i = 0; i < n; i++) { if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } else { // no cancel networkStream.Write(dataToSend, offset, chunk); networkStream.Flush(); offset += chunk; // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); } } Thread.Sleep(5000); // give time to user to react if (windowSendFile.cts.IsCancellationRequested) { //manage cancel operation Console.WriteLine("[Client] - invio annullato "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); return; } if (lastChunk != 0) { networkStream.Write(dataToSend, offset, lastChunk); networkStream.Flush(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.incrementProgressBar(); } }); Console.WriteLine("[Client] - fine invio directory zip "); //File.Delete(zipDir); Console.WriteLine("[Client] - close protocol "); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.endFTP(); } }); } else // if cancel, close { Console.WriteLine("[Client] - close protocol "); MessageFormError mfex = new MessageFormError(firstNameReceiver + " " + lastnameReceiver + " refused file"); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfex.Show(); }); } Thread.Sleep(1000); // give time to sender to see the final state of progress bar // delegate the operation on form to the GUI --> close the send window LANSharingApp.gui.Invoke((MethodInvoker) delegate() { if (windowSendFile != null) { windowSendFile.Close(); } }); } Console.WriteLine("[Client] - chiusa connessione"); } } catch (System.IO.IOException cancelException) { Console.WriteLine(cancelException.ToString()); LANSharingApp.LogFile(cancelException.Message, cancelException.ToString(), cancelException.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } MessageFormError mfe = new MessageFormError("The operation was canceled"); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.errorFTP(); } }); Thread.Sleep(1000); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); } catch (Exception e) { Console.WriteLine(e.ToString()); LANSharingApp.LogFile(e.Message, e.ToString(), e.Source); if (LANSharingApp.sysSoundFlag == 1) { audio_error.Play(); } MessageFormError mfe = new MessageFormError("The selected user is offline, is not possible to satisfy your request"); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.errorFTP(); } }); Thread.Sleep(1000); // delegate the operation on form to the GUI LANSharingApp.gui.Invoke((MethodInvoker) delegate() { mfe.Show(); if (windowSendFile != null) { windowSendFile.Dispose(); windowSendFile.Close(); } }); } finally { //release resources if (File.Exists(zipFileName)) { File.Delete(zipFileName); LANSharingApp.tempFileSend.Remove(zipFileName); } if (zipDir != null) { File.Delete(zipDir); LANSharingApp.tempFileSend.Remove(zipDir); } if (writer != null) { writer.Close(); } if (reader != null) { reader.Close(); } if (client != null) { client.Close(); } } }