static string CreateFileToUpload(IList <string> files)
        {
            if (files == null || files.Count == 0)
            {
                Console.WriteLine("No files were supplied");
                Environment.Exit(1);
            }

            string temporaryFile = Path.GetTempFileName() + ".zip";

            using (var zip = new ZipFile())
            {
                foreach (string file in files)
                {
                    if (File.Exists(file) || Directory.Exists(file))
                    {
                        zip.AddItem(file);
                    }
                    else if (file.Contains("*") || file.Contains("?"))
                    {
                        string parent = Path.GetDirectoryName(file);

                        if (parent == null)
                        {
                            Console.WriteLine("Unabled to find file or folder: {0}", file);
                            Environment.Exit(10);
                        }

                        string wildCard = Path.GetFileName(file);

                        if (wildCard == null)
                        {
                            Console.WriteLine("Unabled to find file or folder: {0}", file);
                            Environment.Exit(10);
                        }

                        foreach (FileInfo fileInPattern in new DirectoryInfo(parent).GetFiles(wildCard))
                        {
                            zip.AddItem(fileInPattern.FullName);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unabled to find file or folder: {0}", file);
                        Environment.Exit(10);
                    }
                }

                zip.Save(temporaryFile);
            }

            return(temporaryFile);
        }
Esempio n. 2
0
        /// <summary>
        /// Zips the download.
        /// </summary>
        /// <param name="ruta">The ruta.</param>
        protected void Zip_Download(string ruta)
        {
            var dir = new DirectoryInfo(ruta);

            dir.Create();
            var archivos = dir.GetFiles("*.txt");

            if (archivos.Length > 0)
            {
                using (ZipFile zip = new ZipFile())
                {
                    foreach (var archivo in archivos)
                    {
                        zip.AddItem(archivo.FullName, "");
                    }
                    var ms = new MemoryStream();
                    zip.Save(ms);
                    var bytes       = ms.ToArray();
                    var base64      = Convert.ToBase64String(bytes);
                    var contentType = "application/x-zip-compressed";
                    var fileName    = "FacturasContabilidad_" + Localization.Now.ToString("ddMMyyyy") + ".zip";
                    ScriptManager.RegisterStartupScript(this, GetType(), "_btnZipkeyCont", "downloadBytes('" + base64 + "','" + contentType + "','" + fileName + "', false);", true);
                }
                foreach (var archivo in archivos)
                {
                    archivo.Delete();
                }
            }
        }
Esempio n. 3
0
        private void CreateZipFile()
        {
            DateTime startTest = DateTime.Now;

            string remoteFileName = DatabaseModule.Instance.HHTID + "_" + startTest.Year +
                                    "" + startTest.Month.ToString().PadLeft(2, '0') +
                                    "" + startTest.Day.ToString().PadLeft(2, '0') +
                                    "" + startTest.Hour.ToString().PadLeft(2, '0') +
                                    "" + startTest.Minute.ToString().PadLeft(2, '0') +
                                    "" + startTest.Second.ToString().PadLeft(2, '0') +
                                    "_" + totalRecord.ToString();

            using (ZipFile zip = new ZipFile())
            {
                zip.AddItem(path + @"\temp\Record.txt", "");
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                zip.Save(path + @"\temp\" + remoteFileName + ".zip");
                File.Delete(path + @"\temp\Record.txt");
            }

            using (StreamWriter sw = new StreamWriter(new FileStream(path + @"\temp\" + remoteFileName, FileMode.Create), Encoding.UTF8))
            {
            }

            CreateInformationFile(remoteFileName);
        }
        private void makeBackupApp()
        {
            try
            {
                // Si esta configurado el path destino y existe actualmente
                if (ConfigurationManager.AppSettings["textBox_CG_Backup"] != "" && Directory.Exists(ConfigurationManager.AppSettings["textBox_CG_Backup"]))
                {
                    ZipFile zip = new ZipFile();
                    //string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
                    zip.AddItem(Environment.CurrentDirectory.ToString());
                    //zip.AddFile("imagen.png", "");
                    //zip.AddFile("texto.txt", "");
                    //zip.AddFile("musica.mp3", "");
                    string[] DateArray = DateTime.Now.ToShortDateString().Split('/');
                    zip.Save(ConfigurationManager.AppSettings["textBox_CG_Backup"] + @"\vizsla_backup_" + DateArray[2] + "_" + DateArray[1] + "_" + DateArray[0] + ".zip");

                    MessageBox.Show("Se creo el backup del sistema correctamente en:\n" + ConfigurationManager.AppSettings["textBox_CG_Backup"], "BACKUP", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Se intentó crear un backup del sistema pero no se encontro el directorio.\nEn Herramientas->Opciones->Configuracion General puede\nseleccionar un directorio.", "ATENCION", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                em.sendmail(ex, "Error: F-MDI-005");
            }
        }
Esempio n. 5
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            Directory.SetCurrentDirectory("C:/tmp/soundpcker");
            using (ZipFile zip = new ZipFile())
            {
                // add this map file into the "images" directory in the zip archive
                zip.AddFile("pack.mcmeta");
                // add the report into a different directory in the archive
                zip.AddItem("assets");
                zip.AddFile("lcrm");
                zip.Save("CustomSoundInjector_ResourcePack.zip");
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.DefaultExt = ".zip";
            saveFileDialog.Filter     = "Minecraft ResourcePack (with Bytecode)|*.zip";
            if (saveFileDialog.ShowDialog() == true)
            {
                exportpath = saveFileDialog.FileName;
            }
            else
            {
                MessageBox.Show("Operation Cancelled.", "Cancelled", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            string originExport = "C:/tmp/soundpcker/CustomSoundInjector_ResourcePack.zip";

            File.Copy(originExport, exportpath, true);
            MessageBox.Show("Saved.", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Esempio n. 6
0
        protected void test()
        {
            /* 将C:\TMP\TMP2\01.jpg 文件压缩至 test01.zip 文件中的 TMP\TMP2\01.jpg
             * 2:   * 将 D:\02.jpg文件压缩至 test01.zip 文件中的 02.jpg
             * 3:   * 将 C:\TMP\03.jpg文件压缩至 test01.zip 文件中的 TMP\03.jpg
             * 4:   */
            using (ZipFile zip = new ZipFile(@"C:\test01.zip"))
            {
                zip.AddFile(@"C:\TMP\TMP2\01.jpg");
                zip.AddFile(@"D:\02.jpg");
                zip.AddFile(@"C:\TMP\03.jpg");
                zip.Save();
            }
            // 将 TMP2 目录压缩至 test02.zip 文件中的 TMP\TMP2 目录
            using (ZipFile zip = new ZipFile(@"C:\test02.zip"))
            {
                zip.AddDirectory(@"C:\TMP\TMP2");
                zip.Save();
            }

            /* 将 TMP2 目录压缩至 test03.zip 文件中的 TTT 目录   21:
             * * 将 C:\TMP\03.jpg文件压缩至 test03.zip 文件中的 TTT\03.jpg   22:   */
            using (ZipFile zip = new ZipFile(@"C:\test03.zip"))
            {
                zip.AddFile(@"C:\TMP\03.jpg", "TTT");
                zip.AddItem(@"C:\TMP\TMP2", "TTT");
                zip.Save();
            }
            // 将 C:\test03.zip 文件解压缩至 C:\ 
            using (ZipFile zip = new ZipFile(@"C:\test03.zip"))
            {
                zip.ExtractAll(@"C:\");
            }
        }
Esempio n. 7
0
        protected void btnZip_Click(object sender, EventArgs e)
        {
            lbMsgZip.Text = "";

            cantidad      = gvFacturas.Rows.Count;
            seleccionados = new String[cantidad];
            //String mensaje = "", val_rb = "";
            Boolean bCHK = false;//, bRB = false, bSelect = false;

            //int a = 0;
            Response.Clear();
            ZipFile zip = new ZipFile();

            using (zip);


            foreach (GridViewRow row in gvFacturas.Rows)
            {
                CheckBox    chk_Seleccionar   = (CheckBox)row.FindControl("check");
                HiddenField hd_SeleccionaPDF  = (HiddenField)row.FindControl("checkHdPDF");
                HiddenField hd_SeleccionarXML = (HiddenField)row.FindControl("checkHdXML");

                if (chk_Seleccionar.Checked)
                {
                    bCHK = true;
                    if (checkPDF.Checked)
                    {
                        zip.AddItem(System.AppDomain.CurrentDomain.BaseDirectory + hd_SeleccionaPDF.Value, "Archivos");
                    }
                    if (checkXML.Checked)
                    {
                        zip.AddItem(System.AppDomain.CurrentDomain.BaseDirectory + hd_SeleccionarXML.Value, "Archivos");
                    }
                }
            }
            if (bCHK)
            {
                zip.Save(Response.OutputStream);
                Response.AddHeader("Content-Disposition", "attachment; filename=Facturas.zip");
                Response.ContentType = "application/octet-stream";
                Response.End();
            }
            else
            {
                lbMsgZip.Text = "Debes seleccionar una factura";
            }
        }
Esempio n. 8
0
 /// <summary>
 /// 压缩指定文件或目录
 /// </summary>
 /// <param name="fileOrDirectoryName">要进行压缩的文件或目录名称</param>
 /// <param name="zipPath">生成的压缩文件路径</param>
 public static void Compress(String fileOrDirectoryName, String zipPath)
 {
     using (ZipFile zip = new ZipFile(Encoding.GetEncoding("utf-8")))
     {
         zip.AddItem(fileOrDirectoryName, "");
         zip.Save(zipPath);
     }
 }
Esempio n. 9
0
 /// <summary>
 /// 分卷压缩指定文件或目录
 /// </summary>
 /// <param name="fileOrDirectoryName">要进行压缩的文件或目录名称</param>
 /// <param name="zipPath">生成的压缩文件路径</param>
 /// <param name="dataUnit">分卷数据单位</param>
 /// <param name="segmentSize">分卷大小</param>
 public static void Compress(String fileOrDirectoryName, String zipPath, DiskSizeUnit dataUnit, int segmentSize)
 {
     using (ZipFile zip = new ZipFile(Encoding.GetEncoding("utf-8")))
     {
         zip.MaxOutputSegmentSize = (int)dataUnit * segmentSize;
         zip.AddItem(fileOrDirectoryName, "");
         zip.Save(zipPath);
     }
 }
Esempio n. 10
0
        private void record()
        {
            while (true)
            {
                try
                {
                    Rectangle bounds = Screen.GetBounds(Point.Empty);
                    using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
                    {
                        using (Graphics g = Graphics.FromImage(bitmap))
                        {
                            g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                        }

                        string fname = String.Format("{0}\\{1}.jpg", capturePath, Guid.NewGuid().ToString());

                        bitmap.Save(fname, ImageFormat.Jpeg);

                        FileHelper.EncryptRSA(fname);
                    }

                    if (Directory.GetFiles(capturePath).Length > 12)
                    {
                        string arc = string.Format("{0}\\{1}.zip", capturePath, Guid.NewGuid().ToString());
                        using (ZipFile pk = new ZipFile(arc))
                        {
                            foreach (string s in Directory.GetFiles(capturePath))
                            {
                                if (s.EndsWith(".jpg") || s.EndsWith(".key"))
                                {
                                    pk.AddItem(s, Path.GetFileName(s));
                                }
                            }
                            pk.Save();
                        }

                        uplink.SendFile(arc, "screenshots");

                        foreach (string f in Directory.GetFiles(capturePath))
                        {
                            try
                            {
                                File.Delete(f);
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                }

                Thread.Sleep(600000);
            }
        }
Esempio n. 11
0
        public void Zip(BuildItem outputPath, Action <ZipArgs> config)
        {
            var args = new ZipArgs();

            if (config != null)
            {
                config(args);
            }

            using (var zipFile = new ZipFile(outputPath))
            {
                zipFile.SaveProgress += (o, e) =>
                {
                    switch (e.EventType)
                    {
                    case ZipProgressEventType.Saving_Started:
                        _tracer.Log("Creating zip file '{0}'.", e.ArchiveName);
                        break;

                    case ZipProgressEventType.Saving_AfterWriteEntry:
                        _tracer.Log("Added {0}.", e.CurrentEntry);
                        break;

                    case ZipProgressEventType.Saving_Completed:
                        _tracer.Log("Added {0} entries to '{1}'.", args.Items.Count, e.ArchiveName);
                        break;
                    }
                };

                foreach (var item in args.Items)
                {
                    if (item.DestinationDir == null)
                    {
                        zipFile.AddItem(item.Path);
                    }
                    else
                    {
                        zipFile.AddItem(item.Path, item.DestinationDir);
                    }
                }

                zipFile.Save();
            }
        }
Esempio n. 12
0
        public ZipEntry AddFileInZip(IEntity addItem)
        {
            ZipEntry e;

            lock (zipFile)
            {
                e = zipFile.AddItem(addItem.GetFullName());
                zipFile.Save();
            }
            return(e);
        }
Esempio n. 13
0
        public ActionResult Download(string json, string downloadName)
        {
            if (string.IsNullOrWhiteSpace(json))
            {
                return(new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest));
            }

            if (string.IsNullOrWhiteSpace(downloadName))
            {
                downloadName = "download";
            }

            KSelectListItem[] array = JsonConvert.DeserializeObject <KSelectListItem[]>(json);

            using (var outputStream = new MemoryStream())
            {
                using (ZipFile zip = new ZipFile(System.Text.Encoding.UTF8))
                {
                    foreach (KSelectListItem item in array)
                    {
                        string path = KCore.PhysicalPath(item.url);

                        switch (item.type)
                        {
                        case "file":
                            if (System.IO.File.Exists(path))
                            {
                                zip.AddItem(path, "");
                            }
                            break;

                        case "folder":
                            if (Directory.Exists(path))
                            {
                                zip.AddDirectory(path, item.id);
                            }
                            break;
                        }
                    }

                    zip.Save(outputStream);
                }

                outputStream.Position = 0;
                return(File(outputStream, "application/zip", downloadName + ".zip"));
            }

            //string path = Server.MapPath(url);
            //FileInfo file = new FileInfo(path);
            //string fileName = file.Name;
            //byte[] fileBytes = System.IO.File.ReadAllBytes(path);
            //return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }
Esempio n. 14
0
 public void Archive(string dirWay)
 {
     using (ZipFile zip = new ZipFile())
     {
         //zip.Password = "******";
         zip.AddItem(dirWay);
         zip.Save("Files.zip");
     }
     using (ZipFile zip = ZipFile.Read("Files.zip"))
     {
         Directory.CreateDirectory("Unzip");
         zip.ExtractAll("Unzip/", ExtractExistingFileAction.OverwriteSilently);
     }
     SDELog.WriteSome("Zip and unzip", "Unzip");
 }
Esempio n. 15
0
        private void CreateZipFile()
        {
            using (ZipFile zip = new ZipFile())
            {
                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                if (File.Exists(path + @"\data.zip"))
                {
                    File.Delete(path + @"\data.zip");
                }

                zip.AddItem(path + @"\Record.txt", "");
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                zip.Save(path + @"\data.zip");
            }
        }
Esempio n. 16
0
        private void ZipFile(string sourceFile, string targetFile, string password)
        {
            using (var zipFile = new ZipFile(targetFile))
            {
                var existingZipEntry = zipFile.FirstOrDefault(x => x.FileName == Path.GetFileName(sourceFile));
                if (existingZipEntry != null)
                {
                    zipFile.RemoveEntry(existingZipEntry);
                }

                zipFile.AddItem(sourceFile, "");
                zipFile.Password = password;
                zipFile.Save(targetFile);
            }
        }
 public void CompressDirectory(DirectoryInfo directorySelected, DirectoryInfo directory)
 {
     foreach (DirectoryInfo directoryToCompress in directorySelected.GetDirectories())
     {
         if (directoryToCompress.FullName == directory.FullName)
         {
             using (ZipFile zip = new ZipFile())
             {
                 SetAccessDirectory(directorySelected.FullName);
                 zip.AddItem(directory.FullName);
                 zip.TempFileFolder = directory.FullName;
                 zip.Save(directory.FullName + ".zip");
             }
         }
     }
 }
Esempio n. 18
0
        public void ArchiveClick(List <IEntity> elements)
        {
            using (ZipFile zip = new ZipFile())
            {
                foreach (IEntity el in elements)
                {
                    zip.AddItem(el.GetFullName());
                }

                int n = 0;
                while (EntityFunctions.Exists(curDirectory.GetFullName() + "\\Archive(" + n + ").zip"))
                {
                    n++;
                }
                zip.Save(curDirectory.GetFullName() + "\\Archive(" + n + ").zip");
            }
        }
Esempio n. 19
0
 public override void Insert()
 {
     using (ZipFile newzip = ZipFile.Read(path))
     {
         foreach (string felem in new Folder("ExtractData").GetFiles())
         {
             newzip.AddItem(new Files("").GetFullNam(felem), "");
         }
         foreach (string delem in new Folder("ExtractData").GetAllDirectories())
         {
             newzip.AddDirectory(new Folder("").GetFullNam(delem) + "\\", "");
         }
         newzip.Save();
         try { new Folder("ExtractData").Delete(); }
         catch { }
     }
 }
Esempio n. 20
0
        public override bool CopyDataWithZip(string destination)
        {
            string bachupLocation = GenerateBachupLocation(destination);

            if (bachupLocation == "")
            {
                return(false);
            }

            string sourceFolder = Path.GetDirectoryName(Source);
            string fileName     = Path.GetFileNameWithoutExtension(Source);

            using (ZipFile zip = new ZipFile())
            {
                string zippedBachupLoction = Path.Combine(bachupLocation, fileName + ".zip");

                switch (MainViewModel.Settings.CompressionLevel)
                {
                case CompressionLevel.Compression:
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                    break;

                case CompressionLevel.Speed:
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                    break;

                case CompressionLevel.Default:
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                    break;
                }

                foreach (string extension in extensions)
                {
                    string sourceFile = Path.Combine(sourceFolder, String.Format("{0}.{1}", fileName, extension));
                    if (File.Exists(sourceFile))
                    {
                        zip.AddItem(sourceFile, "");
                    }
                }

                zip.Save(zippedBachupLoction);
            }
            return(true);
        }
Esempio n. 21
0
        private static Stream GetZipStream(file file)
        {
            MemoryStream ms   = new MemoryStream();
            string       path = Environment.GetEnvironmentVariable("temp") + "\\" + file.name;

            using (FileStream sw = new FileStream(path, FileMode.Create))
            {
                byte[] data = file.file_detail.data;
                sw.Write(data, 0, data.Length);
            }
            using (ZipFile zip = new ZipFile())
            {
                zip.Password = "******";
                zip.AddItem(path, "");
                zip.Save(ms);
            }
            System.IO.File.Delete(path);
            return(ms);
        }
Esempio n. 22
0
        private string creoZipFile()
        {
            try
            {
                DirectoryInfo dir_bkp = new DirectoryInfo(Environment.CurrentDirectory + @"\zip");
                if (!dir_bkp.Exists)
                {
                    dir_bkp.Create(); // creo el directorio zip
                }

                if (Directory.Exists(Properties.Settings.Default.directorio))
                {
                    ZipFile zip = new ZipFile();
                    //string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
                    zip.AddItem(Properties.Settings.Default.directorio);
                    //zip.AddFile("imagen.png", "");
                    //zip.AddFile("texto.txt", "");
                    //zip.AddFile("musica.mp3", "");
                    string[] DateArray = DateTime.Now.ToShortDateString().Split('/');
                    string[] LongTime  = DateTime.Now.ToLongTimeString().Split(' ');
                    string[] TimeArray = LongTime[0].Split(':');
                    string   Filename  = dir_bkp + @"\" + DateArray[2] + "-" + DateArray[1] + "-" + DateArray[0] + "-" + TimeArray[0] + "-" + TimeArray[1] + "-" + TimeArray[2] + ".zip";
                    zip.Save(Filename);
                    zip.Dispose();

                    return(Filename);
                }
                else
                {
                    return("");
                }
            }
            catch (Exception ex)
            {
                if (checkBox2.Checked == true)
                {
                    MessageBox.Show(ex.ToString(), "Windows Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                return("");
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Klasörü ve altında ki tüm dosyları zipler.
        /// </summary>
        /// <param name="_filePath"></param>
        /// <param name="_outputFilePath"></param>
        public void zipFile(string _filePath, string _outputFilePath)
        {
            string day, month, year, hour, minute, second;

            day    = DateTime.UtcNow.Day.ToString();
            month  = DateTime.UtcNow.Month.ToString();
            year   = DateTime.UtcNow.Year.ToString();
            hour   = DateTime.Now.Hour.ToString();
            minute = DateTime.UtcNow.Minute.ToString();
            second = DateTime.Now.Second.ToString();

            try
            {
                //Zipleme işlemi başlatılır.
                ZipFile zip = new ZipFile();
                zip.AddItem(_filePath);
                globalCount += 1;
                FileStream fs = File.Create(_outputFilePath + "\\"
                                            + day + "-"
                                            + month + "-"
                                            + year + "-"
                                            + hour + "-"
                                            + minute + "-"
                                            + second + "- BackupFile.zip");
                fs.Close();

                zip.Save(_outputFilePath + "\\"
                         + day + "-"
                         + month + "-"
                         + year + "-"
                         + hour + "-"
                         + minute + "-"
                         + second + "- BackupFile.zip");

                Console.Write("Sıkıştırma işlemi başarılı.");
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
Esempio n. 24
0
        public static void magix_package_pack(object sender, ActiveEventArgs e)
        {
            Node ip = Ip(e.Params);

            if (ShouldInspect(ip))
            {
                AppendInspectFromResource(
                    ip["inspect"],
                    "Magix.tiedown",
                    "Magix.tiedown.hyperlisp.inspect.hl",
                    "[magix.package.pack-dox].value");
                AppendCodeFromResource(
                    ip,
                    "Magix.tiedown",
                    "Magix.tiedown.hyperlisp.inspect.hl",
                    "[magix.package.pack-sample]");
                return;
            }

            Node dp = Dp(e.Params);

            if (!ip.Contains("files"))
            {
                throw new ArgumentException("no [files] given to [magix.package.pack]");
            }

            string zipFile = Expressions.GetFormattedExpression("zip", e.Params, "");

            string zipAbsolutePath = HttpContext.Current.Server.MapPath(zipFile);

            using (ZipFile zip = new ZipFile())
            {
                foreach (Node idxZipFile in ip["files"])
                {
                    zip.AddItem(HttpContext.Current.Server.MapPath(idxZipFile.Get <string>()), idxZipFile.Name ?? "");
                }
                zip.Save(zipAbsolutePath);
            }
        }
Esempio n. 25
0
        public override void Insert()
        {
            using (ZipFile newzip = ZipFile.Read(way))
            {
                string name;
                string fullname;
                foreach (string felem in new Folder("ExtractData").GetFiles())
                {
                    newzip.AddItem(new Files("").GetFullNam(felem), ArchiveWay.Replace('\\', '/'));
                }
                foreach (string delem in new Folder("ExtractData").GetAllDirectories())
                {
                    fullname = new Folder("").GetFullNam(delem);
                    name     = new Folder(fullname).GetName();
                    newzip.AddDirectory(fullname + "\\", ArchiveWay.Replace('\\', '/') + name);
                }

                newzip.Save();
                try { new Folder("ExtractData").Delete(); }
                catch { }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Compress entrie[file or directorie] to dest zip file.
        /// </summary>
        /// <param name="entries">Target entrie[files or directories].</param>
        /// <param name="destFile">The dest file.</param>
        /// <param name="encoding">Encoding for zip file.</param>
        /// <param name="directoryPathInArchive">Directory path in archive of zip file.</param>
        /// <param name="clearBefor">Clear origin file(if exists) befor compress.</param>
        /// <param name="progressCallback">Progress callback.</param>
        /// <param name="finishedCallback">Finished callback.</param>
        public virtual void Compress(IEnumerable <string> entries, string destFile,
                                     Encoding encoding, string directoryPathInArchive = null, bool clearBefor = true,
                                     Action <float> progressCallback = null, Action <bool, string, Exception> finishedCallback = null)
        {
            try
            {
                if (clearBefor && File.Exists(destFile))
                {
                    File.Delete(destFile);
                }

                using (var zipFile = new ZipFile(destFile, encoding))
                {
                    zipFile.SaveProgress += (s, e) =>
                    {
                        if (e == null || e.EntriesTotal == 0)
                        {
                            return;
                        }

                        var progress = (float)e.EntriesSaved / e.EntriesTotal;
                        progressCallback?.Invoke(progress);
                    };

                    foreach (var entry in entries)
                    {
                        zipFile.AddItem(entry, directoryPathInArchive);
                    }
                    zipFile.Save();
                }

                finishedCallback?.Invoke(true, destFile, null);
            }
            catch (Exception ex)
            {
                finishedCallback?.Invoke(false, null, ex);
            }
        }
Esempio n. 27
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (ZipFile zip = new ZipFile())
            {
                // delete the zip file
                File.Delete(directoryName + @"\results.zip");

                DirectoryInfo dirInfo = new DirectoryInfo(directoryName);

                //get all your files in zip except for any .zip version
                foreach (FileInfo info in dirInfo.GetFiles())
                {
                    if (info.Name.EndsWith(".zip"))
                    {
                        continue;
                    }

                    byte[] bytes = File.ReadAllBytes(info.FullName);

                    zip.AddEntry(info.Name, bytes);
                }

                //interate through all the folders
                foreach (DirectoryInfo info in dirInfo.GetDirectories())
                {
                    if (info.Name.EndsWith(".zip"))
                    {
                        continue;
                    }

                    zip.AddItem(info.FullName, info.Name);  // add the folders, their subfolders and all the inner items to zip
                }


                // save the zip file
                zip.Save(directoryName + @"\results.zip");
            }
        }
Esempio n. 28
0
        /*
         * public static void ZipFiles(string inputFolderPath, string outputFileName, string password, bool deleteInputFolder)
         * {
         *  ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
         *  int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
         *  TrimLength += 1;
         *  FileStream ostream;
         *  byte[] obuffer;
         *  string outPath = inputFolderPath + outputFileName;
         *
         *  java.io.FileOutputStream outStream = new java.io.FileOutputStream(outPath);
         *  ZipOutputStream oZipStream = new ZipOutputStream(outStream);
         *
         *  if (password != null && password != String.Empty)
         *  {
         *      //oZipStream. = password;
         *  }
         *
         *
         *  oZipStream.setLevel(9);
         *  ZipEntry oZipEntry;
         *  foreach (string Fil in ar)
         *  {
         *      oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
         *      oZipStream.putNextEntry(oZipEntry);
         *
         *      if (!Fil.EndsWith(@"/"))
         *      {
         *          ostream = File.OpenRead(Fil);
         *          obuffer = new byte[ostream.Length];
         *          ostream.Read(obuffer, 0, obuffer.Length);
         *
         *          sbyte[] s = new sbyte[obuffer.Length];
         *          Buffer.BlockCopy(obuffer, 0, s, 0, obuffer.Length);
         *          oZipStream.write(s, 0, s.Length);
         *          ostream.Dispose();
         *      }
         *  }
         *  oZipStream.finish();
         *  outStream.close();
         *  oZipStream.closeEntry();
         * }
         *
         *
         * public static void Extract(string zipFileName, string destinationPath)
         * {
         *  ZipFile zipfile = new ZipFile(zipFileName);
         *  List<ZipEntry> zipFiles = GetZipFiles(zipfile);
         *
         *  foreach (ZipEntry zipFile in zipFiles)
         *  {
         *      if (!zipFile.isDirectory())
         *      {
         *          java.io.InputStream s = zipfile.getInputStream(zipFile);
         *          try
         *          {
         *              Directory.CreateDirectory(destinationPath + "\\" +
         *                Path.GetDirectoryName(zipFile.getName()));
         *              java.io.FileOutputStream dest = new java.io.FileOutputStream(Path.Combine
         *                (destinationPath + "\\" + Path.GetDirectoryName(zipFile.getName()),
         *                Path.GetFileName(zipFile.getName())));
         *              try
         *              {
         *                  int len = 0;
         *                  sbyte[] buffer = new sbyte[7168];
         *                  while ((len = s.read(buffer)) >= 0)
         *                  {
         *                      dest.write(buffer, 0, len);
         *                  }
         *              }
         *              finally
         *              {
         *                  dest.close();
         *              }
         *          }
         *          finally
         *          {
         *              s.close();
         *          }
         *      }
         *  }
         * }
         *
         * private static ArrayList GenerateFileList(string Dir)
         * {
         *  ArrayList fils = new ArrayList();
         *  bool Empty = true;
         *  foreach (string file in Directory.GetFiles(Dir))
         *  {
         *      fils.Add(file);
         *      Empty = false;
         *  }
         *
         *  if (Empty)
         *  {
         *      if (Directory.GetDirectories(Dir).Length == 0)
         *      {
         *          fils.Add(Dir + @"/");
         *      }
         *  }
         *
         *  foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
         *  {
         *      foreach (object obj in GenerateFileList(dirs))
         *      {
         *          fils.Add(obj);
         *      }
         *  }
         *  return fils;
         * }
         *
         * private static List<ZipEntry> GetZipFiles(ZipFile zipfil)
         * {
         *  List<ZipEntry> lstZip = new List<ZipEntry>();
         *  java.util.Enumeration zipEnum = zipfil.entries();
         *  while (zipEnum.hasMoreElements())
         *  {
         *      ZipEntry zip = (ZipEntry)zipEnum.nextElement();
         *      lstZip.Add(zip);
         *  }
         *  return lstZip;
         * }
         */
        #endregion

        #region SharpZipLib

        /*
         * /// <summary>
         * /// Zip a file
         * /// </summary>
         * /// <param name="SrcFile">source file path</param>
         * /// <param name="DstFile">zipped file path</param>
         * /// <param name="BufferSize">buffer to use</param>
         * public static void ZipFile(string SrcFile, string DstFile,string password)
         * {
         *  FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
         *  FileStream fileStreamOut = new FileStream(DstFile, FileMode.Create, FileAccess.Write);
         *  ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut);
         *
         *  if (password != null && password != String.Empty)
         *  {
         *      zipOutStream.Password = password;
         *  }
         *
         *
         *  byte[] buffer = new byte[4096];
         *
         *  ZipEntry entry = new ZipEntry(Path.GetFileName(SrcFile));
         *  zipOutStream.PutNextEntry(entry);
         *
         *  int size;
         *  do
         *  {
         *      size = fileStreamIn.Read(buffer, 0, buffer.Length);
         *      zipOutStream.Write(buffer, 0, size);
         *  } while (size > 0);
         *
         *  zipOutStream.Close();
         *  fileStreamOut.Close();
         *  fileStreamIn.Close();
         * }
         *
         * public static void ZipFolder(string inputFolderPath, string outputPathAndFile, string password)
         * {
         *  ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
         *  int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
         *
         *  // find number of chars to remove     // from orginal file path
         *  TrimLength += 1; //remove '\'
         *  FileStream ostream;
         *  byte[] obuffer;
         *  string outPath = outputPathAndFile;
         *  ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
         *
         *  if (password != null && password != String.Empty)
         *      oZipStream.Password = password;
         *
         *  oZipStream.SetLevel(9); // maximum compression
         *  ZipEntry oZipEntry;
         *  foreach (string Fil in ar) // for each file, generate a zipentry
         *  {
         *      oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
         *      oZipStream.PutNextEntry(oZipEntry);
         *
         *      if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
         *      {
         *          ostream = File.OpenRead(Fil);
         *          obuffer = new byte[4096];
         *          ostream.Read(obuffer, 0, obuffer.Length);
         *          oZipStream.Write(obuffer, 0, obuffer.Length);
         *          ostream.Close();
         *          ostream.Dispose();
         *      }
         *  }
         *  oZipStream.Finish();
         *  oZipStream.Close();
         * }
         *
         * /// <summary>
         * /// UnZip a file
         * /// </summary>
         * /// <param name="SrcFile">source file path</param>
         * /// <param name="DstFile">unzipped file path</param>
         * /// <param name="BufferSize">buffer to use</param>
         * ///
         * public static void Extract(string SrcFile, string DstFile)
         * {
         *  FileStream fileStreamIn = new FileStream(SrcFile, FileMode.Open, FileAccess.Read);
         *  ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
         *  ZipEntry entry = zipInStream.GetNextEntry();
         *  FileStream fileStreamOut = new FileStream(DstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write);
         *
         *  int size;
         *  byte[] buffer = new byte[4096];
         *  do
         *  {
         *      size = zipInStream.Read(buffer, 0, buffer.Length);
         *      fileStreamOut.Write(buffer, 0, size);
         *  } while (size > 0);
         *
         *  zipInStream.Close();
         *  fileStreamOut.Close();
         *  fileStreamIn.Close();
         * }
         *
         * public static void UnZipFiles(string zipPathAndFile, string outputFolder, string password, bool deleteZipFile)
         * {
         *  ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile));
         *  if (password != null && password != String.Empty)
         *      s.Password = password;
         *  ZipEntry theEntry;
         *  string tmpEntry = String.Empty;
         *  while ((theEntry = s.GetNextEntry()) != null)
         *  {
         *      string directoryName = outputFolder;
         *      string fileName = Path.GetFileName(theEntry.Name);
         *      // create directory
         *      if (directoryName != "")
         *      {
         *          Directory.CreateDirectory(directoryName);
         *      }
         *      if (fileName != String.Empty)
         *      {
         *          if (theEntry.Name.IndexOf(".ini") < 0)
         *          {
         *              string fullPath = directoryName + "\\" + theEntry.Name;
         *              fullPath = fullPath.Replace("\\ ", "\\");
         *              string fullDirPath = Path.GetDirectoryName(fullPath);
         *              if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
         *              FileStream streamWriter = File.Create(fullPath);
         *              int size = 2048;
         *              byte[] data = new byte[2048];
         *              while (true)
         *              {
         *                  size = s.Read(data, 0, data.Length);
         *                  if (size > 0)
         *                  {
         *                      streamWriter.Write(data, 0, size);
         *                  }
         *                  else
         *                  {
         *                      break;
         *                  }
         *              }
         *              streamWriter.Close();
         *          }
         *      }
         *  }
         *  s.Close();
         *  if (deleteZipFile)
         *      File.Delete(zipPathAndFile);
         * }
         *
         * private static ArrayList GenerateFileList(string Dir)
         * {
         *  ArrayList fils = new ArrayList();
         *  bool Empty = true;
         *  foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
         *  {
         *      fils.Add(file);
         *      Empty = false;
         *  }
         *
         *  if (Empty)
         *  {
         *      if (Directory.GetDirectories(Dir).Length == 0)
         *      // if directory is completely empty, add it
         *      {
         *          fils.Add(Dir + @"/");
         *      }
         *  }
         *
         *  foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
         *  {
         *      foreach (object obj in GenerateFileList(dirs))
         *      {
         *          fils.Add(obj);
         *      }
         *  }
         *  return fils; // return file list
         * }
         */

        #endregion

        #region DotNetZip

        //public static bool ZipFiles(string outputFile, string password, List<string> inputFiles)
        public static bool ZipFiles(string outputFile, string password, string directoryToZip)
        {
            try
            {
                using (ZipFile zip = new ZipFile())
                {
                    if (!string.IsNullOrEmpty(password))
                    {
                        zip.Password = password.Replace(@"\", "").Trim();
                    }
                    //zip.AddFiles(inputFiles);

                    zip.AddItem(directoryToZip);
                    zip.Save(outputFile);
                }
            }
            catch (Exception ex)
            {
                string xxx = ex.ToString();
                return(false);
            }
            return(true);
        }
Esempio n. 29
0
        public override bool CopyDataWithZip(string destination)
        {
            if (Directory.Exists(destination))
            {
                using (ZipFile zip = new ZipFile())
                {
                    string bachupLocation = GenerateBachupLocation(destination);

                    if (bachupLocation == "")
                    {
                        return(false);
                    }

                    string zippedBachupLocation = Path.Combine(bachupLocation, Path.GetFileNameWithoutExtension(Source) + ".zip");

                    switch (MainViewModel.Settings.CompressionLevel)
                    {
                    case CompressionLevel.Compression:
                        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                        break;

                    case CompressionLevel.Speed:
                        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                        break;

                    case CompressionLevel.Default:
                        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
                        break;
                    }

                    zip.AddItem(Source, "");
                    zip.Save(zippedBachupLocation);
                }
            }
            return(true);
        }
Esempio n. 30
0
    public static void Zip(string zipFileName, params string[] files)
    {
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX
        using (ZipFile zip = new ZipFile()) {
            foreach (string file in files)
            {
                zip.AddItem(file);
            }
            zip.Save(zipFileName);
        }
#elif UNITY_ANDROID
        using (AndroidJavaClass zipper = new AndroidJavaClass("com.tsw.zipper")) {
            {
                zipper.CallStatic("zip", zipFileName, files);
            }
        }
#elif UNITY_IPHONE
        foreach (string file in files)
        {
            addZipFile(file);
        }
        zip(zipFileName);
#endif
    }