Exemplo n.º 1
11
        private void button1_Click(object sender, EventArgs e)
        {
            if (Game.ship.id == null)
            {
                throw new InvalidDataException("**** Error! ****\n You have not set a ship ID! Please set one before exporting!!");
            }
            string outputFolder = Path.Combine(Application.StartupPath, Game.ship.id);
            Directory.CreateDirectory(outputFolder);
            Directory.CreateDirectory(Path.Combine(outputFolder, "img"));
            Directory.CreateDirectory(Path.Combine(outputFolder, "img\\ship"));
            Directory.CreateDirectory(Path.Combine(outputFolder, "data"));

            Game.game.ExportLayoutTxt(Path.Combine(outputFolder, "data\\" + Game.ship.layout + ".txt"));
            Game.game.ExportLayoutXML(Path.Combine(outputFolder, "data\\" + Game.ship.layout + ".xml"));
            Game.game.ExportBlueprintXML(Path.Combine(outputFolder, "data\\" + "blueprints.xml.append"), append: true);

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Path.Combine(outputFolder, Game.ship.name + string.Format("-{0:yyyy-MM-dd_hh-mm-ss}", DateTime.Now) + ".ftl"));
            if (Directory.Exists(Path.Combine(outputFolder, "img")))
                zip.AddDirectory(Path.Combine(outputFolder, "img"), "\\img");
            if (Directory.Exists(Path.Combine(outputFolder, "data")))
                zip.AddDirectory(Path.Combine(outputFolder, "data"), "\\data");

            if (Directory.Exists(Path.Combine(outputFolder, "audio")))
                zip.AddDirectory(Path.Combine(outputFolder, "audio"), "\\audio");

            zip.Save();

            System.Diagnostics.Process.Start(outputFolder);
        }
Exemplo n.º 2
2
        public override WFState Run()
        {
            WFState retval = new WFState(WFState.WFStateFail);

            Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(this.FileToProcess);
            string filedir = System.IO.Directory.GetParent(this.FileToProcess).FullName + "\\" + SFWorkflow.WFUtilities.GetNextDirectoryNumber(System.IO.Directory.GetParent(this.FileToProcess).FullName).ToString(); // "\\expanded";
            foreach (Ionic.Zip.ZipEntry ze in zf.EntriesSorted.Where(x => !x.IsDirectory))
            {
                string zedir = ze.FileName.Replace("/", "\\");
                int idx = zedir.LastIndexOf('\\');
                string path = filedir;
                if (idx != -1)
                {
                    path = filedir + "\\" + zedir.Substring(0, idx);
                    zedir = zedir.Substring(idx + 1);
                }
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);
                if (System.IO.Directory.Exists(path))
                {
                    using (System.IO.FileStream fss = new System.IO.FileStream(path + "\\" + zedir, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        ze.Extract(fss);
                        this.OutputFiles.Add(path + "\\" + zedir);
                    }
                }
            }
            retval.Value = WFState.WFStateSuccess;

            return retval;
        }
    public ActionResult Test(long id)
    {
      List<string> list = dataProvider.GeneralRepository.Temp_CreateSpreadsheets(id);
      if (list.Count() == 0) return View("Index");
      string folder = String.Format("{0:yyyyMMdd}", DateTime.Now);
      System.IO.FileInfo fi;
      Response.BufferOutput = true;
      Response.Clear();
      Response.ContentType = "application/zip";
      Response.AddHeader("content-disposition", "attachment; filename=" + folder + ".zip");

      using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
      {
        foreach (string path in list)
        {
          fi = new System.IO.FileInfo(path);
          if (!fi.Exists) continue;
          zip.AddFile(path, folder);
        }
        zip.Save(Response.OutputStream);
      }
      System.Threading.Thread.Sleep(10000);
      Response.End();
      foreach (string path in list)
      {
        fi = new System.IO.FileInfo(path);
        if (!fi.Exists) continue;
        fi.Delete();
      }
      return RedirectToRoute("Index");
    }
Exemplo n.º 4
1
		public void ZipDirectory(string zipFilePath, string directoryPathToCompress, string directoryPathInArchive)
		{
			Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipFilePath);
			zf.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
			zf.AddDirectory(directoryPathToCompress, directoryPathInArchive);
			zf.AddProgress += delegate(object sender, Ionic.Zip.AddProgressEventArgs e)
			{
				Console.WriteLine("\tAdding " + e.CurrentEntry.FileName);
			};
			zf.Save();
		}
Exemplo n.º 5
1
        public static bool CreateZipArchiv(string[] files, string zipArchiv)
        {
            var zipFile = new Ionic.Zip.ZipFile(zipArchiv);

            foreach (var file in files)
            {
                if (File.GetAttributes(file).HasFlag(FileAttributes.Directory))
                {
                    zipFile.AddDirectory(file,new DirectoryInfo(file).Name);
                }
                else
                {
                    zipFile.AddFile(file,String.Empty);
                }
                zipFile.Save();
            }
            return true;
        }
Exemplo n.º 6
1
        public static void CreateZipResponse(List<string> ZipFileList, HttpResponse Response, string ZipFileName, string TempFolder)
        {
            Response.Clear();

            Response.ContentType = "application/octet-stream"; // "application/zip";

            Response.AddHeader("content-disposition", "filename=\"" + ZipFileName + ".zip\"");
            try
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string fileName in ZipFileList)
                    {
                        string path = fileName.Contains("Modules\\" + ZipFileName + "\\")
                                          ? fileName.Substring(fileName.LastIndexOf(ZipFileName + "\\"),
                                                               fileName.Substring(
                                                                   fileName.LastIndexOf(ZipFileName + "\\")).LastIndexOf
                                                                   ("\\"))
                                          : ZipFileName;

                        zip.AddFile(fileName, path);
                    }

                    zip.Save(Response.OutputStream);

                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Response.End();
            }
        }
Exemplo n.º 7
1
        protected override string GenerateCommandLineCommands()
        {
            var cmd = new CommandLineBuilder ();

            if (!UseProguard) {
                // Add the JavaOptions if they are not null
                // These could be any of the additional options
                if (!string.IsNullOrEmpty (JavaOptions)) {
                    cmd.AppendSwitch (JavaOptions);
                }

                // Add the specific -XmxN to override the default heap size for the JVM
                // N can be in the form of Nm or NGB (e.g 100m or 1GB )
                cmd.AppendSwitchIfNotNull ("-Xmx", JavaMaximumHeapSize);

                cmd.AppendSwitchIfNotNull ("-jar ", Path.Combine (ProguardJarPath));
            }

            if (!ClassesOutputDirectory.EndsWith (Path.DirectorySeparatorChar.ToString ()))
                ClassesOutputDirectory += Path.DirectorySeparatorChar;
            var classesFullPath = Path.GetFullPath (ClassesOutputDirectory);

            if (File.Exists (ProguardJarInput))
                File.Delete (ProguardJarInput);
            var zip = new Ionic.Zip.ZipFile (ProguardJarInput, new System.Text.UTF8Encoding (false));
            foreach (var file in Directory.GetFiles (classesFullPath, "*", SearchOption.AllDirectories))
                zip.AddFile (file, Path.GetDirectoryName (file.Substring (classesFullPath.Length)));
            zip.Save ();
            zip.Dispose ();

            var acwLines = File.ReadAllLines (AcwMapFile);
            using (var appcfg = File.CreateText (ProguardGeneratedApplicationConfiguration))
                for (int i = 0; i + 3 < acwLines.Length; i += 4)
                    try {
                        var java = acwLines [i + 3].Substring (acwLines [i + 3].IndexOf (';') + 1);
                        appcfg.WriteLine ("-keep class " + java + " { *; }");
                    } catch {
                        // skip invalid lines
                    }

            var injars = new List<string> ();
            var libjars = new List<string> ();
            injars.Add (ProguardJarInput);
            if (JavaLibrariesToEmbed != null)
                foreach (var jarfile in JavaLibrariesToEmbed)
                    injars.Add (jarfile.ItemSpec);

            using (var xamcfg = File.Create (ProguardCommonXamarinConfiguration))
                GetType ().Assembly.GetManifestResourceStream ("proguard_xamarin.cfg").CopyTo (xamcfg);

            var configs = ProguardConfigurationFiles
                .Replace ("{sdk.dir}", Path.GetDirectoryName (Path.GetDirectoryName (ProguardHome)) + Path.DirectorySeparatorChar)
                .Replace ("{intermediate.common.xamarin}", ProguardCommonXamarinConfiguration)
                .Replace ("{intermediate.references}", ProguardGeneratedReferenceConfiguration)
                .Replace ("{intermediate.application}", ProguardGeneratedApplicationConfiguration)
                .Replace ("{project}", string.Empty) // current directory anyways.
                .Split (';')
                .Select (s => s.Trim ())
                .Where (s => !string.IsNullOrWhiteSpace (s));

            foreach (var file in configs) {
                if (File.Exists (file))
                    cmd.AppendSwitchIfNotNull ("-include ", file);
                else
                    Log.LogWarning ("Proguard configuration file '{0}' was not found.", file);
            }

            libjars.Add (JavaPlatformJarPath);
            if (ExternalJavaLibraries != null)
                foreach (var jarfile in ExternalJavaLibraries.Select (p => p.ItemSpec))
                    libjars.Add (jarfile);

            cmd.AppendSwitch ("\"-injars");
            cmd.AppendSwitch (string.Join (Path.PathSeparator.ToString (), injars.Distinct ().Select (s => '\'' + s + '\''))+"\"");

            cmd.AppendSwitch ("\"-libraryjars");
            cmd.AppendSwitch (string.Join (Path.PathSeparator.ToString (), libjars.Distinct ().Select (s => '\'' + s + '\''))+"\"");

            cmd.AppendSwitch ("-outjars");
            cmd.AppendSwitch ('"' + ProguardJarOutput + '"');

            if (EnableLogging) {
                cmd.AppendSwitchIfNotNull ("-dump ", DumpOutput);
                cmd.AppendSwitchIfNotNull ("-printseeds ", PrintSeedsOutput);
                cmd.AppendSwitchIfNotNull ("-printusage ", PrintUsageOutput);
                cmd.AppendSwitchIfNotNull ("-printmapping ", PrintMappingOutput);
            }

            return cmd.ToString ();
        }
Exemplo n.º 8
0
		public static void DeserializeVoxelAreaData (byte[] bytes, VoxelArea target) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			stream.Write(bytes,0,bytes.Length);
			stream.Position = 0;
			zip = Ionic.Zip.ZipFile.Read(stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			
			zip["data"].Extract (stream2);
			stream2.Position = 0;
			System.IO.BinaryReader reader = new System.IO.BinaryReader(stream2);
			
			int width = reader.ReadInt32();
			int depth = reader.ReadInt32();
			if (target.width != width) throw new System.ArgumentException ("target VoxelArea has a different width than the data ("+target.width + " != " + width + ")");
			if (target.depth != depth) throw new System.ArgumentException ("target VoxelArea has a different depth than the data ("+target.depth + " != " + depth + ")");
			LinkedVoxelSpan[] spans = new LinkedVoxelSpan[reader.ReadInt32()];
			
			for (int i=0;i<spans.Length;i++) {
				spans[i].area = reader.ReadInt32();
				spans[i].bottom = reader.ReadUInt32();
				spans[i].next = reader.ReadInt32();
				spans[i].top = reader.ReadUInt32();
			}
			target.linkedSpans = spans;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Exemplo n.º 9
0
		public static byte[] SerializeVoxelAreaData (VoxelArea v) {
#if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST
			System.IO.MemoryStream stream = new System.IO.MemoryStream();
			System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
			
			writer.Write (v.width);
			writer.Write (v.depth);
			writer.Write (v.linkedSpans.Length);
			
			for (int i=0;i<v.linkedSpans.Length;i++) {
				writer.Write(v.linkedSpans[i].area);
				writer.Write(v.linkedSpans[i].bottom);
				writer.Write(v.linkedSpans[i].next);
				writer.Write(v.linkedSpans[i].top);
			}
			
			//writer.Close();
			writer.Flush();
			Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
			stream.Position = 0;
			zip.AddEntry ("data",stream);
			System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
			zip.Save(stream2);
			byte[] bytes = stream2.ToArray();
			stream.Close();
			stream2.Close();
			return bytes;
#else
			throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST");
#endif
		}
Exemplo n.º 10
0
        private void button1_Click(object sender, EventArgs e)
        {
            //restore game
            var file = (string) listView1.SelectedItems[0].Tag;
            if (string.IsNullOrEmpty(file) || !File.Exists(file) || string.IsNullOrEmpty(_appSettings.GameCatalog)) return;
            var fn = Path.GetFileName(file);
            var res = MessageBox.Show(string.Format("Are you really want to restore savegame:\n'{0}'?\n\nWARNING:Current save game will be replaced with this save!", fn), "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (res != System.Windows.Forms.DialogResult.Yes)
            {
                return;
            }

            try
            {
                using (var zip = new Ionic.Zip.ZipFile(file))
                {
                    foreach (var f in zip)
                    {
                        f.Extract(_appSettings.GameCatalog, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    }
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(string.Format("Some error(s) was rased while we've tryed to restore archived save game:\n'{0}'.\nError message was:\n'{1}'", file, err.Message), "Huston, we have a problem!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show(string.Format("We've successfully restored archived save game:\n'{0}'!", fn), "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Exemplo n.º 11
0
        private void CalculateImageAndTransformationMatrix(string fileName)
        {
            var zipFile = new Ionic.Zip.ZipFile(fileName);
              var mapSize = new Size();
              Transformation = new Transformation();

              // get entry for kml file and image file
              KmlDocument kmlDocument = null;
              foreach (var entry in zipFile)
              {
            if (entry.FileName == entry.LocalFileName && Path.GetExtension(entry.FileName) == ".kml")
            {
              using (var kmlStream = new MemoryStream())
              {
            entry.Extract(kmlStream);
            kmlStream.Position = 0;
            kmlDocument = new KmlDocument(kmlStream);
              }
              break;
            }
              }

              if (kmlDocument != null)
              {
            // we have got a kml document, get map image file stream from it
            foreach (var entry in zipFile)
            {
              if (entry.FileName == kmlDocument.ImageFileName)
              {
            ImageStream = new MemoryStream();
            entry.Extract(ImageStream);
            ImageStream.Position = 0;
            // check if image is QR jpeg
            var ed = QuickRouteJpegExtensionData.FromStream(ImageStream);
            if(ed != null)
            {
              // get transformation matrix from QR jpeg metadata
              Transformation = ed.Sessions.CalculateAverageTransformation();
              ImageStream.Position = 0;
              return;
            }
            else
            {
              // it is not, use normal image bounds
              ImageStream.Position = 0;
              mapSize = Image.FromStream(ImageStream).Size; // need to get image object to get image size
            }
            ImageStream.Position = 0;
            break;
              }
            }
              }

              if (kmlDocument != null && ImageStream != null)
              {
            // finally, calculate the transformation
            Transformation = new Transformation(kmlDocument.LongLatBox, mapSize);
              }
        }
Exemplo n.º 12
0
 static void ExtractZip(string filePath, string destFolder)
 {
     using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(filePath))
     {
         foreach (Ionic.Zip.ZipEntry z in zip)
         {
             z.Extract(destFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
         }
     }
 }
Exemplo n.º 13
0
 /// <summary>
 /// Lazily unzips the specified stream
 /// </summary>
 /// <param name="stream">The zipped stream to be read</param>
 /// <returns>An enumerable whose elements are zip entry key value pairs with
 /// a key of the zip entry name and the value of the zip entry's file lines</returns>
 public static IEnumerable <KeyValuePair <string, IEnumerable <string> > > Unzip(Stream stream)
 {
     using (var zip = ZipFile.Read(stream))
     {
         foreach (var entry in zip)
         {
             yield return(new KeyValuePair <string, IEnumerable <string> >(entry.FileName, ReadZipEntry(entry)));
         }
     }
 }
Exemplo n.º 14
0
 /// <summary>
 /// 压缩文件(传递参数源文件路径和压缩后的文件路径)
 /// </summary>
 /// <param name="srcPath">源文件全路径</param>
 /// <param name="destPath">保存为Zip包的目录</param>
 public static void ZipFileInfo(string srcPath, string destPath)
 {
     using (var zip = new ZipFile())
     {
         Ionic.Zip.ZipEntry zipEntry = zip.AddFile(srcPath, @"\");
         zipEntry.Comment = "Added by Cheeso's CreateZip utility.";
         zip.Comment      = $"This zip archive was created by the CreateZip example application on machine '{Dns.GetHostName()}'";
         zip.Save(destPath);
     }
 }
Exemplo n.º 15
0
        private void SaveContentXml(Ionic.Zip.ZipFile templateFile, System.Xml.XmlDocument contentXml)
        {
            templateFile.RemoveEntry("content.xml");

            System.IO.MemoryStream memStream = new System.IO.MemoryStream();
            contentXml.Save(memStream);
            memStream.Seek(0, System.IO.SeekOrigin.Begin);

            templateFile.AddEntry("content.xml", memStream);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Returns the entry file names contained in a zip file
 /// </summary>
 /// <param name="zipFileName">The zip file name</param>
 /// <returns>An IEnumerable of entry file names</returns>
 public static IEnumerable <string> GetZipEntryFileNames(string zipFileName)
 {
     using (var zip = ZipFile.Read(zipFileName))
     {
         foreach (var entry in zip)
         {
             yield return(entry.FileName);
         }
     }
 }
Exemplo n.º 17
0
 public void Error_AddFile_NonExistentFile()
 {
     string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_NonExistentFile.zip");
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileToCreate))
     {
         zip.AddFile("ThisFileDoesNotExist.txt");
         zip.Comment = "This is a Comment On the Archive";
         zip.Save();
     }
 }
Exemplo n.º 18
0
        public override bool Run()
        {
            using (var zip = new Ionic.Zip.ZipFile(mControl.DestinationFilePathResolvedValue))
            {
                zip.AddFile(mControl.SourceFilePathResolvedValue);
                zip.Save();
            }

            return(true);
        }
Exemplo n.º 19
0
 /// <summary>
 /// 压缩文件(传递参数源文件路径和压缩后的文件路径)
 /// </summary>
 /// <param name="srcPath">源文件全路径</param>
 /// <param name="destPath">保存为Zip包的目录</param>
 public static void ZipFileInfo(string srcPath, string destPath)
 {
     using (var zip = new ZipFile())
     {
         Ionic.Zip.ZipEntry zipEntry = zip.AddFile(srcPath, @"\");
         zipEntry.Comment = "Added by Cheeso's CreateZip utility.";
         zip.Comment = $"This zip archive was created by the CreateZip example application on machine '{Dns.GetHostName()}'";
         zip.Save(destPath);
     }
 }
Exemplo n.º 20
0
        private ActionResult zipFiles(string sid)
        {
            JsonResult   result;
            MessageModel msg;
            string       dirPath = Server.MapPath("~/Temps/" + sid);

            if (!Directory.Exists(dirPath))
            {
                result      = new JsonResult();
                msg         = new MessageModel();
                msg.Code    = 500;
                msg.Message = "文件夹不存在";
                result.Data = msg;
                result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return(result);
            }


            String ext = "*-min.jpg,*-min.jpeg,*-min.png";

            IEnumerable <string> list = Directory.GetFiles(dirPath).ToList()
                                        .Where(item => { return(ext.Contains(Path.GetExtension(item).ToLower())); })
                                        .Where(item => { return(Path.GetFileNameWithoutExtension(item).EndsWith("-min")); });

            using (Ionic.Zip.ZipFile entry = new Ionic.Zip.ZipFile())
            {
                //for(int i = 0;i<list.Length;i++){
                //    String path = list[i];
                //    String filename = Path.GetFileName(path);

                //}

                String zipPath = dirPath + "\\piccompress.zip";

                entry.AddFiles(list, "");



                entry.Save(zipPath);
            }


            result   = new JsonResult();
            msg      = new MessageModel();
            msg.Code = 200;
            string rootpath = Request.ApplicationPath;

            rootpath    = rootpath.EndsWith("/") ? rootpath : rootpath + "/";
            msg.Message = rootpath + "temps/" + sid + "/piccompress.zip";
            result.Data = msg;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return(result);
        }
Exemplo n.º 21
0
        public void webClientProgress()
        {
            string msg = "";
            string msgdot = "";
            int index = 1000;
            int indexdot = 0;
            while (true)
            {
                index++;
                if (index.ToString().Substring(2, 2) == "00")
                {
                    indexdot++;
                    if (indexdot == 1)
                        msgdot = "";
                    else if (indexdot == 2)
                        msgdot = ".";
                    else if (indexdot == 3)
                        msgdot = "..";
                    else if (indexdot == 4)
                        msgdot = "...";
                    else if (indexdot == 5)
                        msgdot = "....";
                    else
                        indexdot = 0;

                }
                Program.msg.send(_m, msg+msgdot);
                if (index > max)
                {
                    msg = "Launching login screen...";
                    break;
                }
                else if ((index > 8000) && (restart))
                {
                    msg = "Extracting files...";

                    Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile("TeraPatcher.zip");
                    zipFile.ExtractAll(Application.StartupPath, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                    zipFile.Dispose();
                    FileDB.TryToDelete("TeraPatcher.zip");
                }
                else if (index > 8000)
                    msg = "Checking memories...";
                else if (index > 7000)
                    msg = "Checking version...";
                else if (index > 5500)
                    msg = "Checking configurations...";
                else if (index > 5000)
                    msg = "Checking files...";
            }
            Process.Start("TeraPatcher.exe", "AeraGaming:MarHazK");
            Program.msg.send(_m, "Exiting");
            Environment.Exit(0);
        }
Exemplo n.º 22
0
        //----------------------------------------------------------------------------+
        //                                  Restore                                   |
        //----------------------------------------------------------------------------+
        public bool Restore_old(string IDBackUp)
        {
            string nomefileBackUp = "";

            Open();

            XmlNode xNode = document.SelectSingleNode("/ROOT/BACKUPS/BACKUP[@ID='" + IDBackUp + "']");

            if (xNode != null)
            {
                nomefileBackUp = xNode.Attributes["File"].Value;
            }

            Close();

            if (nomefileBackUp == "" || !(new FileInfo(cartellaBackUp + nomefileBackUp)).Exists)
            {
                return(false);
            }

            DirectoryInfo rdf = new DirectoryInfo(App.AppDataDataFolder);
            DirectoryInfo uuf = new DirectoryInfo(App.AppDocumentiFolder);

            if (rdf.Exists)
            {
                rdf.Delete(true);
            }

            if (uuf.Exists)
            {
                uuf.Delete(true);
            }

            FileInfo fi = new FileInfo(App.AppMasterDataFile);

            if (fi.Exists)
            {
                fi.Delete();
            }

            fi = new FileInfo(App.AppDocumentiDataFile);

            if (fi.Exists)
            {
                fi.Delete();
            }

            //apro lo zip
            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(cartellaBackUp + nomefileBackUp);
            zip.Password = App.ZipFilePassword;
            zip.ExtractAll(App.AppDataFolder);

            return(true);
        }
 public void ZipDirectory(string zipFilePath, string directoryPathToCompress, string directoryPathInArchive)
 {
     Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipFilePath);
     zf.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
     zf.AddDirectory(directoryPathToCompress, directoryPathInArchive);
     zf.AddProgress += delegate(object sender, Ionic.Zip.AddProgressEventArgs e)
     {
         Console.WriteLine("\tAdding " + e.CurrentEntry.FileName);
     };
     zf.Save();
 }
Exemplo n.º 24
0
        void downloader_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            string[] us             = (string[])e.UserState;
            string   currentVersion = us[0];
            string   downloadPath   = us[1];
            string   executeTarget  = us[2];
            string   localVersion   = us[3];

            if (!downloadPath.EndsWith("\\"))             // Give a trailing \ if there isn't one
            {
                downloadPath += "\\";
            }

            string zipName    = downloadPath + currentVersion + ".zip"; // Download folder + zip file
            string sourcePath = downloadPath + currentVersion;          // Download Path
            string targetPath = CommConst.executePath;                  // 실행폴더
            string exePath    = targetPath + executeTarget;             // Download folder\version\ + executable

            if (new FileInfo(zipName).Exists)
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipName))
                {
                    zip.ExtractAll(downloadPath + currentVersion,
                                   Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }

                CopyFolder(sourcePath, targetPath);

                if (new FileInfo(exePath).Exists)
                {
                    Versions.CreateLocalVersionFile(downloadPath, localVersion, currentVersion);
                    // 집진기 Controller 종료
                    Process[] psList = Process.GetProcessesByName("CADC");
                    if (psList.Length > 0)
                    {
                        psList[0].Kill();
                    }

                    //MessageBox.Show("Path : " + exePath);
                    Process.Start(exePath);
                    Close();
                }
                else
                {
                    //Debug.Write("Problem with download. File does not exist.");
                    MessageBox.Show("Problem with download. File does not exist.", "Updater");
                }
            }
            else
            {
                //Debug.Write("Problem with download. File does not exist.");
                MessageBox.Show("Problem with download. File does not exist.", "Updater");
            }
        }
Exemplo n.º 25
0
        private void btn_TrasferimentoArchiviLocale_Click(object sender, RoutedEventArgs e)
        {
            //richiesta conferma
            Utilities u = new Utilities();

            if (MessageBoxResult.No == u.ConfermaTrasferimentoArchivio())
            {
                return;
            }



            //controllo percorso
            DirectoryInfo origine = new DirectoryInfo(App.AppDataFolder);

            string tmpzipfile = App.AppTempFolder + "zip" + Guid.NewGuid().ToString();

            //Sposto archivio
            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile();
            zip.AddDirectory(origine.FullName);
            zip.Save(tmpzipfile);

            //Interfaccia
            radioButtonArchivioLocale.IsChecked = true;

            //setto variabili globali
            App.AppSetupTipoGestioneArchivio = App.TipoGestioneArchivio.Locale;

            //salvo nuova configurazione
            GestioneLicenza l = new GestioneLicenza();

            l.SalvaInfoDataUltimoUtilizzo();

            //Configuro path applicativi
            u.ConfiguraPercorsi();

            //trasferisco archivio
            DirectoryInfo destinazione = new DirectoryInfo(App.AppDataFolder);

            zip.ExtractAll(destinazione.FullName, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);



            MasterFile.ForceRecreate();

            //interfaccia
            //modifile all'interfaccia dell'ultimo momento
            radioButtonArchivioLocale.IsEnabled      = false;
            radioButtonArchivioRemoto.IsEnabled      = false;
            buttonSelezionaArchivioRemoto.IsEnabled  = false;
            btn_TrasferimentoArchivi.IsEnabled       = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Locale;
            btn_TrasferimentoArchiviLocale.IsEnabled = App.AppSetupTipoGestioneArchivio == App.TipoGestioneArchivio.Remoto;
            MessageBox.Show("Trasferimento archivio avvenuto con successo.");
        }
Exemplo n.º 26
0
        public void Error_AddFile_NonExistentFile()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_NonExistentFile.zip");

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileToCreate))
            {
                zip.AddFile("ThisFileDoesNotExist.txt");
                zip.Comment = "This is a Comment On the Archive";
                zip.Save();
            }
        }
Exemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // -----------------------------------------------------------------------------------------------------------------------------
            string strIdentificadores = Request.QueryString["ids"];
            string strRutaIndicada    = Request.QueryString["ruta"];

            // -----------------------------------------------------------------------------------------------------------------------------
            if (string.IsNullOrEmpty(strIdentificadores) || string.IsNullOrEmpty(strRutaIndicada))
            {
                return;
            }
            // -----------------------------------------------------------------------------------------------------------------------------
            string[] arrIdentificadores = strIdentificadores.Split(new char[] { ',' }), arrSubIdentificadores = null;
            // -----------------------------------------------------------------------------------------------------------------------------
            string strRutaTemporal = Server.MapPath("Temporal");

            if (!strRutaTemporal.EndsWith("\\"))
            {
                strRutaTemporal = string.Format("{0}\\", strRutaTemporal);
            }
            strRutaTemporal = string.Format("{0}{1:ddMMyyyyhhmmssfffff}_{2}\\", strRutaTemporal, DateTime.Now, new Random().Next(10000, 999999));
            // -----------------------------------------------------------------------------------------------------------------------------
            if (!System.IO.Directory.Exists(strRutaTemporal))
            {
                System.IO.Directory.CreateDirectory(strRutaTemporal);
            }
            // -----------------------------------------------------------------------------------------------------------------------------
            // foreach (string strIdentificador in arrIdentificadores)
            // if ((arrSubIdentificadores = strIdentificador.Split(new char[] { ',' })).Length.Equals(3))
            GenerarDocumento(strRutaIndicada, strIdentificadores, strRutaTemporal);
            // -----------------------------------------------------------------------------------------------------------------------------
            string[] arrArchivos = System.IO.Directory.GetFiles(strRutaTemporal);
            if (arrArchivos.Length.Equals(1))
            {
                DescargarArchivo(System.IO.File.ReadAllBytes(arrArchivos[0]), "archivo_doc.docx", "application/msword", System.Text.Encoding.ASCII);
                return;
            }
            // -----------------------------------------------------------------------------------------------------------------------------
            // COMPRIMIR TODOS LOS ARCHIVOS
            string strNombreZip = string.Format("{0}Documentos_{1}.zip", strRutaTemporal, new Random().Next(10000, 999999));

            using (Ionic.Zip.ZipFile objArchivoZip = new Ionic.Zip.ZipFile())
            {
                foreach (string strArchivo in arrArchivos)
                {
                    objArchivoZip.AddFile(strArchivo, string.Empty);
                }
                objArchivoZip.Save(strNombreZip);
            }

            // DESCARGAR
            DescargarArchivo(System.IO.File.ReadAllBytes(strNombreZip), "Documentos.zip", "application/msword", System.Text.Encoding.ASCII);
            // -----------------------------------------------------------------------------------------------------------------------------
        }
Exemplo n.º 28
0
 private void UnZipToDirectory(string dir)
 {
     using (var tempZipFile = new TempFile())
     {
         File.WriteAllBytes(tempZipFile.Path, Resources.ShoppingList);
         using (var zip = new Ionic.Zip.ZipFile(tempZipFile.Path))
         {
             Directory.CreateDirectory(dir);
             zip.ExtractAll(dir);
         }
     }
 }
Exemplo n.º 29
0
        }         // End Sub ZipWithDotNetZip

        public static void ZipAutoExtract()
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                // zip up a directory
                zip.AddDirectory("C:\\project1\\datafiles", "data");

                zip.Comment = "This will be embedded into a self-extracting exe";
                zip.AddEntry("Readme.txt", "This is content for a 'Readme' file that will appear in the zip.");
                zip.SaveSelfExtractor("archive.exe", Ionic.Zip.SelfExtractorFlavor.ConsoleApplication);
            }     // End Using zip
        }         // End Using ZipAutoExtract
Exemplo n.º 30
0
        }         // End Sub ZipToHttpResponse

        public static void ZipWithDotNetZip()
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                // add this map file into the "images" directory in the zip archive
                zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
                // add the report into a different directory in the archive
                zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
                zip.AddFile("ReadMe.txt");
                zip.Save("MyZipFile.zip");
            }     // End Using zip
        }         // End Sub ZipWithDotNetZip
Exemplo n.º 31
0
 public static byte[] ToByteArray(this Ionic.Zip.ZipFile zip)
 {
     if (zip == null)
     {
         throw new ArgumentNullException("zip");
     }
     using (var stream = new MemoryStream())
     {
         zip.Save(stream);
         return(stream.ToArray());
     }
 }
Exemplo n.º 32
0
        public FileResult Zip(Models.Sticker.StickerPackageRequestModel param)
        {
            try
            {
                if (param == null || !param.Id.HasValue)
                {
                    throw new OrgException("Invalid sticker package Id");
                }

                StickerBL bl = new StickerBL();

                var stickerItems = bl.GetStickerItemByPackageId(param.Id.Value);

                if (stickerItems.Count == 0)
                {
                    throw new OrgException("Sticker package not found");
                }

                byte[] zipData = null;

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (var zip = new Ionic.Zip.ZipFile())
                    {
                        foreach (var item in stickerItems)
                        {
                            zip.AddEntry(item.Filename, item.Image);
                        }

                        zip.Save(ms);
                    }

                    zipData = ms.ToArray();
                }

                return(File(zipData, "application/zip", param.Id.Value.ToString() + ".zip"));
            }
            catch (OrgException oex)
            {
                throw new HttpException((int)System.Net.HttpStatusCode.NotFound, oex.Message);
            }
            catch (Exception ex)
            {
                if (AppConfigs.DebugInternalMessage)
                {
                    throw new HttpException((int)System.Net.HttpStatusCode.InternalServerError, ex.Message);
                }
                else
                {
                    throw new HttpException((int)System.Net.HttpStatusCode.NotFound, AppConfigs.InternalErrorMessage);
                }
            }
        }
Exemplo n.º 33
0
        public void Error_AddFile_NonExistentFile()
        {
            string ZipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_NonExistentFile.zip");

            Assert.IsFalse(File.Exists(ZipFileToCreate), "The temporary zip file '{0}' already exists.", ZipFileToCreate);
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(ZipFileToCreate))
            {
                zip.AddFile("ThisFileDoesNotExist.txt");
                zip.Comment = "This is a Comment On the Archive";
                zip.Save();
            }
        }
Exemplo n.º 34
0
        public void UnzipFile(string zipFileName, string toFolder)
        {
            if (!FolderExists(toFolder))
            {
                CreateFolder(toFolder);
            }

            using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(zipFileName))
            {
                zipFile.ExtractAll(toFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            }
        }
Exemplo n.º 35
0
        //加载打包文件
        private MethodTreeNode ImportMethodPackageFile()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Filter = filter;
            dlg.Title  = "请选择要导入的模型包";
            try
            {
                if (dlg.ShowDialog() != true)
                {
                    return(null);
                }

                System.Windows.Forms.FolderBrowserDialog pathdlg = new System.Windows.Forms.FolderBrowserDialog();
                pathdlg.Description = "请选择模型包解压缩的目录";
                if (pathdlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return(null);
                }
                string savepath = pathdlg.SelectedPath;

                //在temp目录中创建rfdi目录
                string rfdiDir = Path.Combine(Path.GetTempPath(), "rfdi_nodeExport");
                if (Directory.Exists(rfdiDir))  //如果存在,删除当前文件夹
                {
                    Directory.Delete(rfdiDir, true);
                }
                Directory.CreateDirectory(rfdiDir);

                using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(dlg.FileName))
                {
                    zip.ExtractAll(rfdiDir);
                }
                string[] subdirs = Directory.GetDirectories(rfdiDir);

                string extractdir = Path.Combine(savepath, Path.GetFileName(subdirs[0]));
                int    index      = 1;
                while (Directory.Exists(extractdir))
                {
                    extractdir = Path.Combine(savepath, Path.GetFileName(subdirs[0]) + index);
                    index++;
                }
                Directory.CreateDirectory(extractdir);
                DirectoryCopy(subdirs[0], extractdir);
                Directory.Delete(rfdiDir, true);

                return(CreateMethodNodeFromDirectory(extractdir));
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 36
0
        public void ExtractEmbededZipFileContentToFolder(string resourceName, System.Reflection.Assembly assembly, string destinationFolder)
        {
            var zipFileName = this.GetTempFileName();

            this.ExtractEmbededResourceToFile(resourceName, assembly, zipFileName, null);

            using (Ionic.Zip.ZipFile zipFile = Ionic.Zip.ZipFile.Read(zipFileName))
            {
                zipFile.ExtractAll(destinationFolder, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            }

            this.DeleteFile(zipFileName);
        }
Exemplo n.º 37
0
 private void ExtractAllFilesOfType(Ionic.Zip.ZipFile z, string ext)
 {
     foreach (Ionic.Zip.ZipEntry e in z.Entries.Where(f => f.FileName.Contains(ext)))
     {
         StatusFloater.Invoke(new System.Action(() => StatusFloater.lblSubStatus.Text = e.FileName.Substring(e.FileName.LastIndexOf("/") + 1)));
         if (!File.Exists(m_analysisPath + "\\" + e.FileName.Substring(e.FileName.LastIndexOf("/") + 1)))
         {
             FileStream fs = new FileStream(m_analysisPath + "\\" + e.FileName.Substring(e.FileName.LastIndexOf("/") + 1), FileMode.Create);
             e.Extract(fs);
             fs.Close();
         }
     }
 }
        private void DeployPackage(string targetDir)
        {
            // Get the zip file name.
            string outputZip = this.project.GetOutputAssembly(this.ConfigName);

            // MPF is lazy and hardcodes ".exe" to the output assembly. We hardcode it to zip instead.
            outputZip = outputZip.Substring(0, outputZip.Length - 4) + ".zip";

            // Extract the contents.
            var file = new Ionic.Zip.ZipFile(outputZip);

            file.ExtractAll(targetDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
        }
Exemplo n.º 39
0
        public override bool Run()
        {
            var zipFileName = Path.ChangeExtension(mControl.DestinationFilePathResolvedValue, Common.FileExtensions.ZipFileExtension);

            using (var zip = new Ionic.Zip.ZipFile(zipFileName))
            {
                var files = Directory.EnumerateFiles(mControl.SourceFilePathResolvedValue, "*", SearchOption.AllDirectories);
                zip.AddFiles(files);
                zip.Save();
            }

            return(true);
        }
Exemplo n.º 40
0
 public static void ZipDirectories()
 {
     OnClipboardDirectory((dir) => {
         var directories = Directory.GetDirectories(dir);
         foreach (var element in directories)
         {
             using (var zip = new Ionic.Zip.ZipFile(Encoding.GetEncoding("gbk"))) {
                 zip.AddDirectory(element);
                 zip.Save(element + ".zip");
             }
         }
     });
 }
Exemplo n.º 41
0
        /* Extract ZipFile */
        public static void ExtractZipFile(string filePath, string serverZipExtractPath)
        {
            string zipToUnpack     = filePath;
            string unpackDirectory = serverZipExtractPath;

            using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(zipToUnpack))
            {
                foreach (Ionic.Zip.ZipEntry e in zip1)
                {
                    e.Extract(unpackDirectory, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }
Exemplo n.º 42
0
 void 压缩子目录ToolStripMenuItemClick(object sender, EventArgs e)
 {
     Helpers.OnClipboardFileSystem((path) => {
         var directories = Directory.GetDirectories(path);
         foreach (var element in directories)
         {
             using (var zip = new Ionic.Zip.ZipFile(Encoding.GetEncoding("gbk"))) {
                 zip.AddDirectory(element);
                 zip.Save(element + ".zip");
             }
         }
     });
 }
Exemplo n.º 43
0
        public void ZipFileS2(string _processby, Main2 main)
        {
            string sPath = Application.StartupPath + "\\Output\\" + Main2.outputFolder;
            string dPath = Application.StartupPath + "\\Output\\AFT_" + main.batchfile + "_" + _processby + ".zip";

            DeleteZipfile();
            ZipFile.CreateFromDirectory(sPath, dPath);
            Ionic.Zip.ZipFile zips = new Ionic.Zip.ZipFile(dPath);
            zips.AddItem(Application.StartupPath + "\\Head");
            zips.Save();
            // CopyZipFile2(_processby, main);
            DeleteFiles(".SQL");
        }
Exemplo n.º 44
0
        public void LongNamesJsonSerialization_NormalAndZip_DotNetZip_BlockCopyMethod()
        {
            List <GPSPoint1> points = new List <GPSPoint1>();
            Random           rand   = new Random();

            for (int i = 0; i < 1000; i++)
            {
                points.Add(new GPSPoint1((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), DateTime.Now));
            }

            string output = JsonConvert.SerializeObject(points);

            byte[] bytes = new byte[output.Length * sizeof(char)];
            System.Buffer.BlockCopy(output.ToCharArray(), 0, bytes, 0, bytes.Length);

            for (int i = 1; i < bytes.Length; i += 2)
            {
                Assert.AreEqual(0, bytes[i]);
            }
            var length1 = bytes.Length;

            byte[] compressedData;
            using (MemoryStream str = new MemoryStream())
            {
                using (var zip = new Ionic.Zip.ZipFile())
                {
                    zip.CompressionLevel = CompressionLevel.BestCompression;
                    zip.AddEntry("README.txt", bytes);
                    zip.Save(str);
                }
                var r = str.Length;
                compressedData = str.ToArray();
            }

            //test for unzipping
            using (MemoryStream dest = new MemoryStream())
            {
                using (MemoryStream str = new MemoryStream(compressedData))
                {
                    var entry      = Ionic.Zip.ZipFile.Read(str);
                    var firstEntry = entry.First();
                    firstEntry.Extract(dest);
                }
                byte[] endData = dest.ToArray();
                for (int i = 0; i < endData.Length; i++)
                {
                    Assert.AreEqual(bytes[i], endData[i]);
                }
            }
        }
Exemplo n.º 45
0
 /// <summary>
 /// 压缩目录下的所有文件
 /// </summary>
 /// <param name="filePath">源文件根目录</param>
 /// <param name="savePath">保存为Zip包的目录</param>
 public static void ZipDirFileInfo(string filePath, string savePath)
 {
     using (var zip = new ZipFile())
     {
         //读取文件夹下面的所有文件
         string[] fileNames = Directory.GetFiles(filePath);
         foreach (string fileName in fileNames)
         {
             Ionic.Zip.ZipEntry zipEntry = zip.AddFile(fileName, @"\");
             zipEntry.Comment = "Added by Cheeso's CreateZip utility.";
         }
         zip.Comment = $"This zip archive was created by the CreateZip example application on machine '{Dns.GetHostName()}'";
         zip.Save(savePath);
     }
 }
Exemplo n.º 46
0
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = "application/zip";
            response.AppendHeader("content-disposition", "attachment; filename=" + FileName);

            using (var zipFile = new Ionic.Zip.ZipFile())
            {
                foreach (var e in this.Entries)
                {
                    zipFile.AddEntry(e.FileName, e.BytesStream);
                }
                zipFile.Save(response.OutputStream);
            }
        }
Exemplo n.º 47
0
        /// <summary>
        /// 压缩一个文件返回流信息
        /// </summary>
        /// <param name="filePath">源文件服务器路径</param>
        /// <param name="fileName">压缩文件名</param>
        /// <returns></returns>
        public static byte[] ZipFileOneInfo(string filePath, string fileName)
        {
            using (var zipFile = new ZipFile(Encoding.UTF8))
            {
                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    zipFile.AddEntry(fileName, fileStream);
                    using (var memoryStream = new MemoryStream())
                    {
                        zipFile.Save(memoryStream);
                        return memoryStream.ToArray();
                    }

                }
            }
        }
Exemplo n.º 48
0
 public ActionResult Test2(long id)
 {
   System.IO.FileInfo fi = new System.IO.FileInfo(dataProvider.GeneralRepository.Temp_CreateSpreadsheetW(id));
   string folder = System.IO.Path.GetFileNameWithoutExtension(fi.FullName);
   if (!fi.Exists) return RedirectToRoute("Index");
   Response.Clear();
   Response.ContentType = "application/zip";
   Response.AddHeader("content-disposition", "attachment; filename=" + folder + ".zip");
   using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
   {
     zip.AddFile(fi.FullName, folder);
     zip.Save(Response.OutputStream);
   }
   System.Threading.Thread.Sleep(30000);
   Response.End();
   fi.Delete();
   return View("Index");
 }
Exemplo n.º 49
0
        public static void DownloadFiles(List<string> archives, HttpContext httpContext)
        {
            if (archives.Count == 0)
                return;
            FileAttributes attr1 = System.IO.File.GetAttributes(archives[0]);
            if (archives.Count == 1 && ((attr1 & FileAttributes.Directory) != FileAttributes.Directory))
            {
                string filename = Path.GetFileName(archives[0]);
                httpContext.Response.Buffer = true;
                httpContext.Response.Clear();
                httpContext.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
                httpContext.Response.ContentType = "application/octet-stream";
                httpContext.Response.WriteFile(archives[0]);
            }
            else
            {
                string zipName = String.Format("archive-{0}.zip",
                                      DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                httpContext.Response.Buffer = true;
                httpContext.Response.Clear();
                httpContext.Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
                httpContext.Response.ContentType = "application/zip";
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string path in archives)
                    {
                        try
                        {
                            FileAttributes attr = System.IO.File.GetAttributes(path);

                            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                                zip.AddDirectory(path, Path.GetFileNameWithoutExtension(path));
                            else
                                zip.AddFile(path, "");
                        }
                        catch (Exception)
                        {
                        }
                    }
                    zip.Save(httpContext.Response.OutputStream);
                }
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Do a simple zip of the given directory
        /// </summary>
        /// <param name="sourceDirPath"></param>
        /// <param name="targetZipPath"></param>
        /// <returns>True if succeeds</returns>
        public static bool zipChangeSetDir(string sourceDirPath, string targetZipPath)
        {
            try
            {
                if (string.IsNullOrEmpty(targetZipPath) || !Directory.Exists(sourceDirPath) || string.IsNullOrEmpty(sourceDirPath))
                    return false;

                createDirForFile(targetZipPath);

                using (Ionic.Zip.ZipFile zfile = new Ionic.Zip.ZipFile())
                {
                    zfile.AddDirectory(sourceDirPath);
                    //zfile.AddDirectory(sourceDirPath + "\\new");
                    zfile.Save(targetZipPath);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// Primary entry point to the program
        /// </summary>
        static void Main(string[] args)
        {
            //Document the process:
            Console.WriteLine("QuantConnect.ToolBox: AlgoSeek Options Processor ");
            Console.WriteLine("=================================================");
            Console.WriteLine("The AlgoSeek Options Processor transforms AlgoSeek options ticks into the LEAN Algorithmic Trading Engine Data Format.");
            Console.WriteLine("Three parameters are required: ");
            Console.WriteLine("   1> Output resolution of the LEAN data. (either minute, second or hour)");
            Console.WriteLine("   2> Source Directory of Zipped AlgoSeek Options Data.");
            Console.WriteLine("   3> Destination Directory of LEAN Data Folder. (Typically located under Lean/Data)");
            Console.WriteLine(" ");
            Console.WriteLine("NOTE: THIS WILL OVERWRITE ANY EXISTING FILES.");
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

            if (args.Length > 0) _resolution = args[0];
            if (args.Length > 1) _sourceDirectory = args[1];
            if (args.Length > 2) _destinationDirectory = args[2];

            //Validate the user input:
            Validate(_sourceDirectory, _destinationDirectory, _resolution);

            //Remove the final slash to make the path building easier:
            _sourceDirectory = StripFinalSlash(_sourceDirectory);
            _destinationDirectory = StripFinalSlash(_destinationDirectory);

            //Get all the zip files to process
            Console.WriteLine("Counting Files...");
            var zipFiles = new DirectoryInfo(_sourceDirectory).GetFiles("*.zip");
            Console.WriteLine("Processing {0} Files ...", zipFiles.Count());

            // Dummy zip file
            var zipOut = new Ionic.Zip.ZipFile();

            foreach (var zipFile in zipFiles)
            {
                var starttime = DateTime.Now;
                Console.WriteLine("Reading " + zipFile.Name);

                var listTick = new List<TmpTick>();

                using (var reader = Compression.Unzip(zipFile.FullName, out zipOut))
                    while (!reader.EndOfStream)
                    {
                        var tick = new TmpTick(zipFile.Name.Split('.')[1], reader.ReadLine());
                        if (tick.IsInvalid) continue;

                        if (listTick.Count == 0)
                        {
                            listTick.Add(tick);
                            continue;
                        }

                        var lastRoundTime = listTick.Last().Time.RoundDown(_span);

                        if (lastRoundTime == tick.Time.RoundDown(_span))
                        {
                            listTick.Add(tick);
                            continue;
                        }

                        Console.Write("\r" + lastRoundTime.ToString(@"HH\:mm\:ss") + "\t" + listTick.Count + "\t" + (DateTime.Now - starttime).ToString(@"hh\:mm\:ss\.fff"));

                        WriteLeanCsvFiles(listTick);

                        listTick.Add(tick);
                    }

                WriteLeanCsvFiles(listTick);

                CompressLeanCSV(zipFile);

                Console.WriteLine("... done!");
            }

            Console.WriteLine("All done! Press any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 52
0
        public override int DebugLaunch( uint grfLaunch )
        {
            CCITracing.TraceCall();

            var clientApp = new MFilesAPI.MFilesClientApplication();
            var apiVersion = clientApp.GetAPIVersion().Display;
            MFilesAPI.Vault vault = null;

            var vaultName = GetConfigurationProperty( "TestVault", true );
            MFilesAPI.VaultConnection vaultConnection;
            try
            {
                vaultConnection = clientApp.GetVaultConnection( vaultName );
            }
            catch
            {
                throw new Exception( "The document vault '" + vaultName + "' was not found." );
            }
            string vaultGuid = vaultConnection.GetGUID();

            // Get the M-Files install directory from the registry.
            var hklm64 = RegistryKey.OpenBaseKey( RegistryHive.LocalMachine, RegistryView.Registry64 );
            var mfKey = hklm64.OpenSubKey( @"Software\Motive\M-Files\" + apiVersion );
            var installDir = (string)mfKey.GetValue( "InstallDir" );
            mfKey.Close();
            hklm64.Close();

            // Log out to free the current application.
            try
            {
                vault = clientApp.BindToVault( vaultName, IntPtr.Zero, false, true );
                if( vault != null ) vault.LogOutWithDialogs( IntPtr.Zero );
            }
            catch { }

            // Deploy the application.
            var relativePath = string.Format( @"Client\Apps\{0}\sysapps\{1}",
                vaultGuid, this.project.GetProjectProperty( "Name" ) ?? "unnamed" );
            var targetDir = Path.Combine( installDir, relativePath );

            // If the directory exists, remove it so there's no residue files left.
            if( Directory.Exists( targetDir ) ) { Directory.Delete( targetDir, true ); }
            Directory.CreateDirectory( targetDir );

            // Extract the Zip contents to the target directory.
            var outputZip = this.project.GetOutputAssembly( this.ConfigName );

            // MPF is lazy and hardcodes ".exe" to the output assembly. We hardcode it to zip instead.
            outputZip = outputZip.Substring( 0, outputZip.Length - 4 ) + ".zip";

            var file = new Ionic.Zip.ZipFile( outputZip );
            file.ExtractAll( targetDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently );

            var launchMode = ( GetConfigurationProperty( "LaunchMode", false ) ?? "" ).ToLowerInvariant();
            vault = clientApp.BindToVault( vaultName, IntPtr.Zero, true, false );
            if( launchMode == "powershell" )
            {
                var builtInState = InitialSessionState.CreateDefault();
                builtInState.Variables.Add( new SessionStateVariableEntry(
                    "vaultName", vaultName, "Name of the vault used for testing." ) );
                builtInState.Variables.Add( new SessionStateVariableEntry(
                    "vault", vault, "M-Files Vault" ) );
                Runspace runspace = RunspaceFactory.CreateRunspace( builtInState );
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript( GetConfigurationProperty( "LaunchPSScript", false ) ?? "" );
                pipeline.Invoke();
                runspace.Close();
            }
            else
            {
                var mfilesPath =
                    clientApp.GetDriveLetter() + ":\\" +
                    vaultName + "\\" +
                    GetConfigurationProperty( "LaunchMFilesPath", false );

                try
                {
                    // We need to log in first - otherwise explorer.exe can't find the folders.
                    Process.Start( "explorer.exe", string.Format( "\"{0}\"", mfilesPath ) );
                }
                catch { }
            }

            return VSConstants.S_OK;
        }
Exemplo n.º 53
0
 /// <summary>
 /// 将一个压缩文件集合返回压缩后的字节数
 /// </summary>
 /// <param name="filesPath">源文件集合</param>
 /// <returns></returns>
 public static byte[] ZipFilesInfo(IEnumerable<string> filesPath)
 {
     using (var zipFile = new ZipFile())
     {
         foreach (var filePath in filesPath)
         {
             Ionic.Zip.ZipEntry zipEntry = zipFile.AddFile(filePath, @"\");
         }
         zipFile.Comment =
             string.Format("This zip archive was created by the CreateZip example application on machine '{0}'",
                 Dns.GetHostName());
         using (MemoryStream memoryStream = new MemoryStream())
         {
             zipFile.Save(memoryStream);
             return memoryStream.ToArray(); //将流内容写入字节数组
         }
     }
 }
Exemplo n.º 54
0
        private void CheckUpdate()
        {
            string str3 = "";
            if (NetworkInterface.GetIsNetworkAvailable() == false)
            {
                try
                {
                    str3 = new WebClient().DownloadString("http://www.xxxthedartkprogramerxxx.net//Update/PeXploit/Update.txt");
                    if (appversion == str3)
                    {
                        updateavaialable = false;

                    }
                    else
                    {
                        updateavaialable = true;
                    }
                }
                catch
                {
                    updateavaialable = false;
                }
            }
            if (updateavaialable == true)
            {
                Welcome.INFO = ("Update Found");
                DialogResult result = MessageBox.Show("Update Is Avaialbe Do You Want To Download It ?", "Update Found", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (DialogResult.Yes == result)
                {
                    Welcome.INFO = ("Downloading...");
                    this.Hide();
                    Download_WIndow dw = new Download_WIndow();
                    dw.url = "http://www.xxxthedartkprogramerxxx.net//Download/PeXploit.zip";
                    dw.ShowDialog();
                    this.Show();
                    Thread.Sleep(1000);
                    if (File.Exists(Application.StartupPath + "\\PeXploit.zip"))
                    {
                        this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracting", "Extracting Update", ToolTipIcon.Info);
                        Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Application.StartupPath + @"\Pexploit.zip");
                        zip.ExtractAll(Application.StartupPath + @"\");
                        Thread.Sleep(1000);
                        this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracted", "Opening File", ToolTipIcon.Info);
                        MessageBox.Show("Mainually Delete The Old Files Thanks");
                        System.Diagnostics.Process.Start(Application.StartupPath + @"\PeXploit\PeXploit.exe");
                        Application.Exit();
                    }
                    File.Delete(Application.StartupPath + @"\Pexploit.zip");
                }
            }
            else
            {
                Welcome.INFO = ("You Have The Latest Verion Of PeXploit");
            }
        }
Exemplo n.º 55
0
 private void saveGame()
 {
     if (string.IsNullOrEmpty(_appSettings.SaveCatalog) || string.IsNullOrEmpty(_appSettings.GameCatalog))
         return;
     var dt = DateTime.MinValue;
     var path = _appSettings.GameCatalog;
     using (var zipfile = new Ionic.Zip.ZipFile())
     {
         RecursiveArchivate(path, zipfile, "", ref dt);
         if (dt <= _lastArchiveTime) return;
         var name = Path.GetFileNameWithoutExtension(_appSettings.GameCatalog);
         var filename = string.Format("{0}\\savegame_{1}_{2}.zip", _appSettings.SaveCatalog, dt.ToString("yyMMdd-HHmmss"), name);
         zipfile.Save(filename);
         File.SetLastWriteTime(filename, dt);
     }
     updateList();
     updateUI();
 }
Exemplo n.º 56
0
        public DLWindow()
        {
            Application.EnableVisualStyles();
            _wc = new WebClient();
            _wc.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e)
            {
                var nlt = e.BytesReceived / 1024 + "KB";
                var npbv = 0;
                ProgressBarStyle npbs;

                if (e.TotalBytesToReceive <= 0)
                {
                    nlt += " / ?";
                    npbs = ProgressBarStyle.Marquee;
                }
                else
                {
                    nlt += " / " + e.TotalBytesToReceive / 1024 + "KB - " + e.ProgressPercentage + "%";
                    npbs = ProgressBarStyle.Blocks;
                    npbv = e.ProgressPercentage;
                }
                try
                {
                    Invoke(new Action(delegate
                    {
                        label1.Text = nlt;
                        progressBar1.Style = npbs;
                        progressBar1.Value = npbv;
                    }));
                }
                catch { }
            };

            _wc.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e)
            {
                if (e.Cancelled)
                {
                    return;
                }
                if (e.Error != null)
                {
                    MessageBox.Show("Error!\n" + e.Error.Message);
                    return;
                }

                Ionic.Zip.ZipFile zf;
                try
                {
                    zf = new Ionic.Zip.ZipFile(ServerHandler.ProcessHandler.ResolveJarPath("%ad%\\cb_artifact.zip"));
                }
                catch (Exception ex) { MessageBox.Show(Resources.DLWindow_DLWindow_ + ex.Message); return; }
                BeginInvoke(new Action(delegate
                {
                    try
                    {
                        foreach (var zfe in zf)
                        {
                            if (!zfe.IsDirectory)
                            {
                                FileStream fs;
                                zfe.Extract(fs = File.Open(ServerHandler.ProcessHandler.ResolveJarPath(Config.Default["jarpath"]),
                                    FileMode.OpenOrCreate, FileAccess.Write));
                                fs.Close();
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(Resources.DLWindow_DLWindow_ + ex.Message);
                    }
                    this.Close();

                }));
            };

            InitializeComponent();
        }
Exemplo n.º 57
-1
        /// <summary>
        /// Descomprime el archivo especificado en el directorio correspondiente
        /// </summary>
        /// <param name="fi"></param>
        public static string decompressFile(FileInfo fi)
        {
            string name = fi.Name.ToString().Replace(".pkg", "");

            FileInfo zipfile = fi.CopyTo(name + ".zip" ,true);
            string dirDestino = fi.Directory.FullName + @"\" + name;
            if(Directory.Exists(dirDestino)==true)
            {
                Directory.Delete(dirDestino,true);

            }
            Directory.CreateDirectory(dirDestino);

            fi.Delete();
            Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipfile.FullName);
            zf.ExtractAll(dirDestino,Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            Console.WriteLine("extraido aunque no lo parezca");
            return dirDestino;
            /*
            using (FileStream infile = fi.OpenRead())
            {
                string curfile = fi.FullName;
                string originalName = curfile.Remove(curfile.Length - fi.Extension.Length);

                using (FileStream outfile = File.Create(originalName))
                {

                    using (GZipStream decompress = new GZipStream(infile, CompressionMode.Decompress))
                    {
                        decompress.CopyTo(outfile);
                    }
                }
            }
                 */
        }
Exemplo n.º 58
-1
        public string Run(List<string> files)
        {
            if (files == null)
                files = new List<string>();

            if (d != null)
            {                
                if (d.inputType ==  Db.actionZipInputType.custom)
                    files.AddRange(d.file);
                               
               
                string folder = d.folderToSave;
                if (folder.EndsWith("\\"))
                    folder = folder.Substring(0, folder.Length - 1);
                string fullZipName = folder + "\\" + d.zipFileName;

                if (System.IO.File.Exists(fullZipName))
                    System.IO.File.Delete(fullZipName);

                Ionic.Zip.ZipFile z = new Ionic.Zip.ZipFile();
                foreach (string f in files)
                {
                    z.AddFile(f);                       
                }
                z.Save(fullZipName);

                return fullZipName;
            }
            return string.Empty;
        }
Exemplo n.º 59
-1
 /// <summary>
 /// 压缩文件夹,文件架下面包含文件夹
 /// </summary>
 /// <param name="filePath">源文件夹路径</param>
 /// <param name="savePath">保存为Zip包的目录</param>
 public static void ZipDirInfo(string filePath, string savePath)
 {
     using (var zip = new ZipFile())
     {
         zip.StatusMessageTextWriter = Console.Out;
         zip.AddDirectory(filePath, @"\");
         zip.Save(savePath);
     }
 }
Exemplo n.º 60
-1
        public void Save(string path, string fileName, string content, string password)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(path))
            {
                zip.Password = password;
                zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;

                if (zip["" + fileName + ""] != null)
                {
                    zip.RemoveEntry(fileName);
                }

                zip.AddEntry(fileName, content, System.Text.Encoding.UTF8);
                zip.Save(path);
            }
        }