AddFiles() public method

This method adds a set of files to the ZipFile.

Use this method to add a set of files to the zip archive, in one call. For example, a list of files received from System.IO.Directory.GetFiles() can be added to a zip archive in one call.

For ZipFile properties including Encryption, , SetCompression, , ExtractExistingFile, ZipErrorAction, and CompressionLevel, their respective values at the time of this call will be applied to each ZipEntry added.

public AddFiles ( System fileNames ) : void
fileNames System /// The collection of names of the files to add. Each string should refer to a /// file in the filesystem. The name of the file may be a relative path or a /// fully-qualified path. ///
return void
        /// <summary>
        /// This method generates the cbz file from the images in the manga book.
        /// </summary>
        /// <param name="mangaBook"></param>
        /// <param name="saveLocation">Location to save the manga book cbz file.</param>
        public void Generate(MangaBook mangaBook, string saveLocation)
        {
            OperationStatus.StartedMangaBookFileCreation(mangaBook);

            Collection<string> imageSaveLocationList = new Collection<string>();

            mangaBook.SaveLocationPath = Path.Combine(saveLocation, mangaBook.FileName());
            using (ZipFile zip = new ZipFile(mangaBook.SaveLocationPath))
            {
                SavePagesAsPhysicalFiles(mangaBook, saveLocation, imageSaveLocationList);

                // Get all pages from save location and create cbz file.

                zip.AddFiles(imageSaveLocationList);
                zip.Save();

                // Delete the temporary files.

                foreach (string path in imageSaveLocationList)
                {
                    File.Delete(path);
                }
            }

            OperationStatus.CompletedMangaBookFileCreation(mangaBook);
        }
Exemplo n.º 2
0
        public static void doBackup()
        {
            try {
                List<string> bkpfiles = new List<string>();
                DateTime fecha = DateTime.Now;
                string format = "yyyyMMdd";    // Use this format
                String[] pacientes = Directory.GetFiles(Configuracion.getDirectorioPacientes(),"*.dat");
                String[] hhcc = Directory.GetFiles(Configuracion.getDirectorioHC() ,"*.dat");
                String[] imagenes = Directory.GetFiles(Configuracion.getDirectorioImagenes());
                foreach(string s in pacientes)
                    bkpfiles.Add(s);
                foreach(string s in hhcc)
                    bkpfiles.Add(s);
                foreach(string s in imagenes)
                    bkpfiles.Add(s);
                String backupfile = Configuracion.getDirectorioBackup() + "\\" + "Backup_" + fecha.ToString(format) + ".zip";
                ZipFile zip = new ZipFile();
                zip.AddFiles(bkpfiles.ToArray());
                zip.Save(backupfile);
                MessageBox.Show("Backup realizado correctamente.\n" + backupfile);

            } catch (Exception e) {
                MessageBox.Show("Error en el proceso de backup!\n" + e.Message);
            }
        }
Exemplo n.º 3
0
    public static void AddFilesToZip(string zipPath, List<string> files)
    {
        var v = new Ionic.Zip.ZipFile(zipPath);

        v.AddFiles(files);
        v.Save();
    }
Exemplo n.º 4
0
        public static void backupSSF()
        {
            //verifica se existe o diretório, caso não exista será criado
            string dirAnteriores = Library.appDir + "\\ssf\\anteriores\\";
            if (!System.IO.Directory.Exists(dirAnteriores))
            {
                System.IO.Directory.CreateDirectory(dirAnteriores);
            }

            //verifica se existe o diretório, caso não exista será criado
            string dirZipados = Library.appDir + "\\ssf\\zipados\\";
            if (!System.IO.Directory.Exists(dirZipados))
            {
                System.IO.Directory.CreateDirectory(dirZipados);
            }

            //backup ssf
            System.IO.DirectoryInfo dirSSF = new System.IO.DirectoryInfo(appDir + "\\ssf");

            string[] filePaths = System.IO.Directory.GetFiles(dirSSF.ToString(), "*.ssf");

            ZipFile zip =
                new ZipFile(dirZipados + DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year +
                    DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".zip");
            zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
            zip.AddFiles(filePaths);
            zip.Save();

            //move todos os arquivos
            foreach (string file in filePaths)
                System.IO.File.Move(file, dirAnteriores + System.IO.Path.GetFileName(file));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Serialize
        /// </summary>
        /// <param name="site">site</param>
        /// <param name="path">path</param>
        /// <returns></returns>
        public void Serialize(Site site, string path)
        {
            if (site == null)
            {
                throw new ArgumentException("site");
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("stream");
            }

            var tempPath = Path.GetTempPath() + "site.xml";
            using (var stream = File.Create(tempPath))
            {
                var serializer = new XmlSerializer(typeof(Site));
                serializer.Serialize(stream, site);
            }

            var packagePath = path + Path.DirectorySeparatorChar + site.Name + ".wbp";
            if (File.Exists(packagePath))
            {
                File.Delete(packagePath);

            }
            using (ZipFile package = new ZipFile(packagePath, Console.Out))
            {
                package.AddFile(tempPath, string.Empty);
                package.AddFiles(site.Resources.Select(r => r.TextData).Where(File.Exists), "resources");
                package.Save();
            }
        }
Exemplo n.º 6
0
    static public void AddFilesToZip(string zipPath, List <string> files)
    {
        var v = new Ionic.Zip.ZipFile(zipPath);

        v.AddFiles(files);
        v.Save();
    }
Exemplo n.º 7
0
        private static void CreateArchive(IEnumerable<JobInfo> jobs, string archiveFile)
        {
            File.Delete(archiveFile);

              var zipper = new ZipFile(archiveFile);
              zipper.AddFiles(jobs.Select(it => it.ImageFile));
              zipper.Save();
        }
Exemplo n.º 8
0
 private void CreateArchive(Stream outputStream)
 {
     using (var zip = new ZipFile())
     {
         zip.AddFiles(EnumerateLogFiles(GetStartDate(), GetEndDate()), true, "");
         zip.Save(outputStream);
     }
 }
Exemplo n.º 9
0
		public static void CompressFiles(IEnumerable<string> filesPaths, string compressedFilePath)
		{
			using (var zip = new ZipFile())
			{
				zip.AddFiles(filesPaths, false, "");
				zip.Save(compressedFilePath);
			}
		}
Exemplo n.º 10
0
 public override void ExecuteResult(ControllerContext context)
 {
     using (ZipFile zf = new ZipFile())
     {
         zf.AddFiles(_files, false, "");
         context.HttpContext.Response.ContentType = "application/zip";
         context.HttpContext.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
         zf.Save(context.HttpContext.Response.OutputStream);
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// 压缩文件
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="save"></param>
 public static void Compress(string[] filename, string save, string dir = "", Encoding encoding = default(Encoding))
 {
     if (encoding == default(Encoding))
     {
         encoding = Encoding.Default;
     }
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
     {
         zip.AddFiles(filename, dir);
         zip.Save(save);
     }
 }
Exemplo n.º 12
0
 static void Main(string[] args)
 {
     using (ZipFile zip = new ZipFile())
     {
         string[] files = Directory.GetFiles(@".");
         files = (from o in files where !o.Contains(".z") && !o.Contains("zip.exe") select o).ToArray();
         zip.AddFiles(files);
         zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
         zip.MaxOutputSegmentSize = 99 * 1024 * 1024;   // 2mb
         zip.Save("zip.zip");
         //Console.ReadLine();
     }
 }
Exemplo n.º 13
0
 /// <summary>
 /// zips attachments, takes parameters directly from the "files" list
 /// </summary>
 public void Zip_Attachments(object sender, RoutedEventArgs e)
 {
     zipProgressBar.Visibility = Visibility.Visible;
     zipProgressOverlay.Visibility = Visibility.Visible;
     SendMailTab_message.IsEnabled = false;
     SendMailTab_subject.IsEnabled = false;
     SendMailTab_to.IsEnabled = false;
     zipProgressBar.Value = 0;
     zipProgressBar.Maximum = files.Count();
     ZipFile zip = new ZipFile();
     zip.AddFiles(files);
     zip.SaveProgress += zip_SaveProgress;
     Directory.CreateDirectory("Zipped");
     zip.Save("Zipped\\test.zip");
 }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            Stream outStream = new MemoryStream();
            using (ZipFile zip = new ZipFile())
            {
                string[] files = Directory.GetFiles(@"C:\ForRobot");
                zip.AddFiles(files,"");
                zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
                //zip.Save(@"C:\ForRobot.zip");
                zip.Save(outStream);
             }

            Console.WriteLine(outStream.Length);
            outStream.Close();
            Console.ReadLine();
        }
Exemplo n.º 15
0
        public static Stream CompressOutStream(string[] files, string dir = "", Encoding encoding = default(Encoding))
        {
            if (encoding == default(Encoding))
            {
                encoding = Encoding.Default;
            }
            MemoryStream stream = new MemoryStream();

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
            {
                zip.AddFiles(files, dir);
                zip.Save(stream);
                stream.Position = 0;
            }
            return(stream);
        }
Exemplo n.º 16
0
        public bool CrearZip(string pathDestino, IList<string> pathsArchivos)
        {
            bool zipped = false;

            if (pathsArchivos.Count > 0)
            {
                using (var loanZip = new ZipFile())
                {
                    //var filePath = Path.Combine()
                    loanZip.AddFiles(pathsArchivos, false, "");
                    loanZip.Save(pathDestino);
                    zipped = true;
                }
            }

            return zipped;
        }
Exemplo n.º 17
0
        public void SaveZipFile(string folderPath, string fileName)
        {
            using (var zip = new ZipFile())
            {
                string zippedFilePath = this.fileSystem.Path.Combine(folderPath, fileName);

                var pdfFiles = this.fileSystem.Directory.GetFiles(folderPath, "*.pdf");
                if (pdfFiles.Any())
                {
                    zip.AddFiles(pdfFiles, @"\");
                    zip.Save(zippedFilePath);
                }
                else
                {
                    throw new Exception(string.Format("There were no PDF files that were present in directory {0}", folderPath));
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="files">文件夹 => 文件集合</param>
        /// <param name="encoding">编码</param>
        /// <returns></returns>
        public static Stream CompressOutStream(Dictionary <string, List <string> > files, Encoding encoding = default(Encoding))
        {
            if (encoding == default(Encoding))
            {
                encoding = Encoding.Default;
            }
            MemoryStream stream = new MemoryStream();

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
            {
                foreach (string key in files.Keys)
                {
                    zip.AddFiles(files[key], key);
                }
                zip.Save(stream);
                stream.Position = 0;
            }
            return(stream);
        }
Exemplo n.º 19
0
        public static string ZipConvertedAudioFiles(IEnumerable<string> convertedAudioFilenames)
        {
            var zippedFileName = string.Empty;

            try
            {
                zippedFileName = FileNameGenerationHelper.GenerateFilename();
                var zip = new ZipFile(Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), zippedFileName));
                zip.AddFiles(convertedAudioFilenames.Select(caf => Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), caf)), false, "");
                zip.Save();
                zip.Dispose();
            }
            catch (Exception e)
            {
                throw new ZipException(e.Message);
            }

            return zippedFileName;
        }
Exemplo n.º 20
0
        static void Main()
        {
            // get paths to everything
            var basePath = Environment.CurrentDirectory.Up(3);
            var driverPath = Path.Combine(basePath, @"RavenLinqpadDriver\bin\Release");
            var commonPath = Path.Combine(basePath, @"RavenLinqpadDriver.Common\bin\Release");
            var releaseDir = Path.Combine(basePath, "Release", "");
            Directory.CreateDirectory(releaseDir);

            // get version from driver assembly
            var assemblyPath = Path.Combine(driverPath, "RavenLinqpadDriver.dll");
            var assembly = Assembly.LoadFile(assemblyPath);
            var version = assembly.GetName().Version;

            // zip up both release folders as lpx files
            using (var ms = new MemoryStream())
            using (var releaseZip = new ZipFile())
            using (var lpx40 = new ZipFile())
            {
                var releaseZipPath = Path.Combine(releaseDir, string.Format("RavenLinqpadDriver {0}.zip", version));

                // 40 driver lpx file
                lpx40.AddFiles(GetFiles(driverPath), "");
                lpx40.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);
                releaseZip.AddEntry("RavenLinqpadDriver.lpx", ms);

                // reset the memorystream
                releaseZip.Save(releaseZipPath);
                ms.SetLength(0);

                // common
                releaseZip.AddFile(Path.Combine(commonPath, "RavenLinqpadDriver.Common.dll"), "Common");

                // readme
                releaseZip.AddFile(Path.Combine(basePath, "readme.txt"), "");
                releaseZip.Save(releaseZipPath);
            }

            // open
            Process.Start(releaseDir);
        }
Exemplo n.º 21
0
 public static bool Zip(string[] files, string outputfile, string password = "")
 {
     bool result = false;
     using (ZipFile zip = new ZipFile())
     {
         if (password.Length > 0)
             zip.Password = password;
         zip.AddFiles(files);
         zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
         zip.CompressionMethod = CompressionMethod.Deflate;
         zip.Encryption = EncryptionAlgorithm.WinZipAes256;
         zip.Save(outputfile);
         zip.ZipError += (o, e) =>
         {
             result = false;
         };
         result = true;
     }
     return result;
 }
        protected void crearZip(string url, string rutaGuarda, string ID)
        {
            try
            {
                //Listamos los archivos que trae el directorio
                DirectoryInfo directorySelected = new DirectoryInfo(url);
                List<FileInfo> fi = new List<FileInfo>(directorySelected.GetFiles());
                //Definimos le nombre que llevara nuestro archio comprimido
                string fileName = "OC Mov. " + ID + ".zip";
                //Limpiamos le stream
                Response.Clear();
                //Metenmos la lista de archivos que contiene el directorio en una lista de tipo string
                List<string> lista = new List<string>();

                foreach (FileInfo fileToString in fi)
                {
                    //Le concatenamos la ruta donde se va a leer el archivo
                    lista.Add(rutaGuarda + fileToString.ToString());
                }
                //Creamos el archivo
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                Response.ContentType = "application/x-zip-compressed";
                //Llenamos le archivo con la lista
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddFiles(lista, ID);
                    zip.Save(Response.OutputStream);
                }
            }
            catch (System.Exception ex)
            {
                throw new Exception("Error " + ex.Message);

            }
            finally
            {
                Response.End();
                Response.Close();
            }
        }
Exemplo n.º 23
0
        public static bool CreateZipFileFromFiles(List<string> inputFiles, string outputFile)
        {
            try
            {
                using (ZipFile zip = new ZipFile())
                {

                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                    zip.FlattenFoldersOnExtract = true;
                    zip.AddFiles(inputFiles, false, "");
                    zip.Save(outputFile);
                }
            }
            catch (Exception ex)
            {
                Functions.WriteLineToLogFile("Could not create zip file.");
                Functions.WriteExceptionToLogFile(ex);
                return false;
            }

            return true;
        }
Exemplo n.º 24
0
        //public static byte[] Compress(
        //    string file,
        //    CompressionLevel compressionLevel = Ionic.Zlib.CompressionLevel.BestCompression,
        //    CompressionMethod compressionMethod = CompressionMethod.Deflate,
        //    EncryptionAlgorithm encryption = EncryptionAlgorithm.WinZipAes256,
        //    string password = "")
        //{
        //    return Compress(new string[] { file }, compressionLevel, compressionMethod, encryption, password);
        //}

        public static byte[] Compress(
            string[] files,
            //CompressionLevel compressionLevel = Ionic.Zlib.CompressionLevel.BestCompression,
            //CompressionMethod compressionMethod = CompressionMethod.Deflate,
            //EncryptionAlgorithm encryption = EncryptionAlgorithm.WinZipAes256,
            string password = "")
        {
            var memoryStream = new MemoryStream();
            using (var zip = new ZipFile())
            {
                CompressionLevel compressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                CompressionMethod compressionMethod = CompressionMethod.Deflate;
                EncryptionAlgorithm encryption = EncryptionAlgorithm.WinZipAes256;

                bool hasError = false;
                if (!String.IsNullOrEmpty(password))
                {
                    zip.Password = password;
                }
                zip.AddFiles(files);
                zip.CompressionLevel = compressionLevel;
                zip.CompressionMethod = compressionMethod;
                zip.Encryption = encryption;
                zip.FlattenFoldersOnExtract = true;
                zip.ZipError += (o, e) =>
                {
                    hasError = true;
                };
                if (hasError)
                    return null;
                zip.Save(memoryStream);
                //byte[] bytes = memoryStream.ToArray();
                //File.WriteAllBytes(@"C:\Users\benjamin\AeroFS\Visual Studio 2012\Projects\restless-honey-seeker\serverDotNet\Server\DataFromClient\" + DateTime.Now.Ticks + ".zip", bytes);
                //return bytes;
            }
            return memoryStream.ToArray();
        }
Exemplo n.º 25
0
        //[HttpPost]
        public ActionResult DownloadStaffDocuments()
        {
            string path   = Server.MapPath("~/UploadedFile/");
            bool   exists = Directory.Exists(path);//check folder exsit or not

            string[]      Filenames          = Directory.GetFiles(path);
            List <string> directoryFileNames = Directory.GetFiles(path).ToList();
            string        staffName          = "Tayyab";


            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                if (exists)
                {
                    if (directoryFileNames.Count != 0)
                    {
                        zip.AddFiles(directoryFileNames, "");
                        //Generate zip file folder into loation
                        zip.Save(path + staffName + ".zip");//Folder where we want to save zip file
                    }
                }
            }
            return(RedirectToAction("Index", "Product"));
        }
Exemplo n.º 26
0
    private void CreateOnTheFlyZip(string bookid, string userid)
    {
        AddCounter(bookid, userid);

        string DirectoryPath = Server.MapPath(String.Format("../E-library/{0}/Pages", bookid));

        if (Directory.Exists(DirectoryPath))
        {
             //Set ZipFile Name
            string filename = string.Format("Book_{0}-{1}{2}{3}.zip", bookid, DateTime.Now.ToString("MM"), DateTime.Now.ToString("dd"), DateTime.Now.ToString("yyyy"));

            Response.Clear();
            Response.BufferOutput = false;
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "filename=" + filename);
            using (ZipFile Zip = new ZipFile())
            {
                string[] Files = Directory.GetFiles(DirectoryPath);
                Zip.AddFiles(Files, "Zip");
                Zip.Save(Response.OutputStream);
            }
            Response.Close();
        }
    }
Exemplo n.º 27
0
        private void ZipProject(List<string> files)
        {
            var existingFileFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files.zip");

            if (File.Exists(existingFileFullPath))
            {
                File.Delete(existingFileFullPath);
            }

            using (ZipFile zip = new ZipFile())
            {
                zip.AddFiles(files);

                zip.Save("files.zip");
            }
        }
Exemplo n.º 28
0
        public ActionResult Download(int id)
        {
            //TODO: File/folder filter for package has not been implemented. For example we do not need xml gallery state file.
            byte[] output = null;

            GalleryRuntime.BuildGalleryOutput(id);

            var content = GalleryRuntime.LoadGalleryContent(id);

            using (var package = new ZipFile())
            {
                var root = GalleryRuntime.GetGalleryDevPath(id);

                package.AddFiles(Directory.GetFiles(root));

                foreach (var item in Directory.GetDirectories(root))
                    package.AddDirectory(item, item.Substring(root.Length).TrimStart(Path.DirectorySeparatorChar));

                foreach (var item in content.SystemFilePathes)
                {
                    try
                    {
                        package.RemoveEntry(item);
                    }
                    catch (Exception ex)
                    {
                        this.Logger.WriteError(ex);
                    }
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    package.Save(stream);

                    stream.Position = 0;
                    output = stream.ToArray();
                }
            }

            return this.File(output, "application/zip");
        }
Exemplo n.º 29
0
        public void Create_EmitTimestampOptions()
        {
            string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            for (int j = 0; j < 3; j++)
            {
                for (int k = 0; k < 3; k++)
                {
                    string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Create_EmitTimestampOptions-{0}-{1}.zip", j, k));
                    using (var zip = new ZipFile())
                    {
                        if (j == 1) zip.EmitTimesInUnixFormatWhenSaving = false;
                        else if (j == 2) zip.EmitTimesInUnixFormatWhenSaving = true;

                        if (k == 1) zip.EmitTimesInWindowsFormatWhenSaving = false;
                        else if (k == 2) zip.EmitTimesInWindowsFormatWhenSaving = true;

                        zip.AddFiles(files, "files");
                        zip.Save(zipFileToCreate);
                    }

                    Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate), "The Zip file has the wrong number of entries.");

                    using (var zip = FileSystemZip.Read(zipFileToCreate))
                    {
                        for (int i = 0; i < zip.Entries.Count; i++)
                        {
                            if (j == 2)
                                Assert.AreEqual<ZipEntryTimestamp>(ZipEntryTimestamp.Unix, zip[i].Timestamp & ZipEntryTimestamp.Unix,
                                    "Missing Unix timestamp (cycle {0},{1}) (entry {2}).", j, k, i);
                            else
                                Assert.AreEqual<ZipEntryTimestamp>(ZipEntryTimestamp.None, zip[i].Timestamp & ZipEntryTimestamp.Unix,
                                    "Unix timestamp is present when none is expected (cycle {0},{1}) (entry {2}).", j, k, i);

                            if (k == 1)
                                Assert.AreEqual<ZipEntryTimestamp>(ZipEntryTimestamp.None, zip[i].Timestamp & ZipEntryTimestamp.Windows,
                                    "Windows timestamp is present when none is expected (cycle {0},{1}) (entry {2}).", j, k, i);
                            else
                                Assert.AreEqual<ZipEntryTimestamp>(ZipEntryTimestamp.Windows, zip[i].Timestamp & ZipEntryTimestamp.Windows,
                                    "Missing Windows timestamp (cycle {0},{1}) (entry {2}).", j, k, i);

                            Assert.AreEqual<ZipEntryTimestamp>(ZipEntryTimestamp.DOS, zip[i].Timestamp & ZipEntryTimestamp.DOS,
                                "Missing DOS timestamp (entry (cycle {0},{1}) (entry {2}).", j, k, i);
                        }
                    }
                }
            }
        }
Exemplo n.º 30
0
        public void DoubleSave_wi10735()
        {
            string zipFileToCreate1 = "DoubleSave.1.zip";
            string zipFileToCreate2 = "DoubleSave.2.zip";
            string dirToZip = "dirToZip";
            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            using (var zip = new ZipFile())
            {
                zip.AddFiles(files);
                zip.Save(zipFileToCreate1);
                zip.Save(zipFileToCreate2);
            }
        }
Exemplo n.º 31
0
        public void ContainsEntryTest()
        {
            string zipFileToCreate = "ContainsEntry.zip";
            string dirToZip = "dirToZip";
            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            using (var zip = new ZipFile())
            {
                zip.AddFiles(files);
                zip.Save(zipFileToCreate);
            }

            Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate));
            using (var zip2 = FileSystemZip.Read(zipFileToCreate))
            {
                for (int i=0; i < 28; i++)
                {
                    int n = _rnd.Next(files.Length);
                    TestContext.WriteLine("Checking {0}", files[n]);
                    Assert.IsTrue(zip2.ContainsEntry(files[n]), "missing entry");
                }
            }
        }
Exemplo n.º 32
0
        //protected void UploadMultipleFiles(object sender, EventArgs e)
        //{

        //    foreach (HttpPostedFile postedFile in FileUpload2.PostedFiles)
        //    {
        //        string fileName = Path.GetFileName(postedFile.FileName);
        //        postedFile.SaveAs(Server.MapPath("~/PDF/") + fileName);
        //    }
        //    lblSuccess.Text = string.Format("{0} files have been uploaded successfully.", FileUpload1.PostedFiles.Count);
        //}


        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //// For test

            // String  strCC = Request.Form["dlemailCC"].ToString();
            // string[] _mailCC = null;
            //if (strCC != null)
            //{
            //    _mailCC = strCC.Split(',');
            //}

            //////////

            //String tmpMail;
            //tmpMail = Request.Form["dlemail"].ToString();

            //       string[] mailTo = new string[] {tmpMail };
            List <string> myCollection  = new List <string>();
            List <string> ZipCollection = new List <string>();

            ///  UploadMain PDF

            if (UploadMain())
            {
                HttpFileCollection fileCollection = Request.Files;
                for (int i = 1; i < fileCollection.Count; i++)
                {
                    HttpPostedFile uploadfile = fileCollection[i];
                    string         fileName   = Path.GetFileName(uploadfile.FileName);
                    if (uploadfile.ContentLength > 0)
                    {
                        uploadfile.SaveAs(Server.MapPath("~/AttachFiles/") + fileName);
                        myCollection.Add(Server.MapPath("~/AttachFiles/") + fileName);
                        lblMessage.Text += fileName + "  Saved  Successfully<br>";

                        BLL.Upload _BLL = new BLL.Upload();
                        _BLL.Update_AttachFile(Doc, 1);
                    }

                    else // Update AttachFile 1 = 0
                    {
                        BLL.Upload _BLL = new BLL.Upload();
                        _BLL.Update_AttachFile(Doc, 0);
                    }
                }


                //Zip

                using (Ionic.Zip.ZipFile compress = new Ionic.Zip.ZipFile())
                {
                    string zipfilepath = Server.MapPath("~/AttachFiles/");
                    compress.AddFiles(myCollection.ToArray(), Doc.doc_id);
                    compress.Save(Server.MapPath("~/AttachFiles/") + Doc.doc_id + ".zip");
                }

                Response.Redirect("DataDocument.aspx");
            }


            //     Helper.Utility.SendEmail("Test ODS",mailTo, _mailCC , myCollection.ToArray(),"This is link",false);

            //       Response.Redirect("Default.aspx");
        }
Exemplo n.º 33
0
        public void ParallelDeflateStream_Create_CompareSpeeds()
        {
            string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var files = TestUtilities.GenerateFilesFlat(dirToZip, _rnd.Next(5) + 5, 2048 * 1024 + _rnd.Next(200000));

            var ts = new TimeSpan[2];

            // 2 sets of 2 cycles: first set is warmup, 2nd is timed.
            // Actually they're both timed but times for the 2nd set
            // overwrite the times for the 1st set.
            // Within a set, the first run is non-parallel, 2nd is timed parallel.
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("ParallelDeflateStream_Create.{0}.{1}.zip", i, j));

                    var sw = new System.Diagnostics.Stopwatch();
                    sw.Start();
                    using (var zip = new ZipFile())
                    {
                        if (j == 0)
                            zip.ParallelDeflateThreshold = -1L; // disable parallel deflate
                        else
                            zip.ParallelDeflateThreshold = 128 * 1024;  // threshold for parallel deflating

                        zip.AddFiles(files, "fodder");

                        zip.Save(zipFileToCreate);
                    }
                    sw.Stop();

                    BasicVerifyZip(zipFileToCreate);

                    Assert.AreEqual<int>(files.Length, TestUtilities.CountEntries(zipFileToCreate),
                                         "The zip file created has the wrong number of entries.");
                    ts[j] = sw.Elapsed;
                    TestContext.WriteLine("Cycle {0},{1}, Timespan: {2}", i, j, ts[j]);
                }
            }
            Assert.IsTrue(ts[1] < ts[0], "Parallel deflating is NOT faster than single-threaded, for large files.");
        }
Exemplo n.º 34
0
        void ConvertToJSON(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            try
            {
                using (Stream zipStream = e.Argument as Stream)
                {
                    using (MemoryStream exStream = ExtractToStream(zipStream))
                    {
                        string directory = addDelimiter(SaveDirectory) + @"tmp\";

                        addresses.Clear();
                        TextFieldParser parser = new TextFieldParser(exStream, Encoding.GetEncoding("Shift_JIS"));
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");

                        ProgressStatus = "パース中";

                        ProgressMaxNum = 100;
                        ProgressValue  = 0;

                        int count = 0;
                        //CSVファイルを1行ずつパースしてcollectionに追加
                        while (parser.EndOfData == false)
                        {
                            string[] columns = parser.ReadFields();
                            addresses.Add(new Models.Address(columns));

                            count++;

                            //1件ごとにやると細かすぎてうまくいかないので
                            if ((count % 1233) == 0)
                            {
                                Worker.ReportProgress(1);
                            }
                        }

                        ProgressMaxNum = addresses.GroupBy(x => x.ZipCode.Substring(0, 3)).Count();
                        ProgressValue  = 0;

                        ProgressStatus = "個別ファイル作成中";

                        //フォルダがなければ作成
                        if (!System.IO.Directory.Exists(directory))
                        {
                            System.IO.Directory.CreateDirectory(directory);
                        }

                        //郵便番号の上3ケタごとに出力
                        foreach (var row in addresses.GroupBy(x => x.ZipCode.Substring(0, 3)))
                        {
                            //重複は除外しファイル出力
                            SerializeToJson(row.Distinct(new AddressComparer()).OrderBy(x => x.ZipCode).ToList(), directory + "zip" + row.Key + ".txt");
                            Worker.ReportProgress(1);
                        }

                        ProgressStatus = "ZIP圧縮中";

                        //ZipFileを作成する
                        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                        {
                            zip.AddFiles(System.IO.Directory.GetFiles(directory), "");
                            zip.Save(addDelimiter(SaveDirectory) + @"zipcode.zip");
                            System.IO.Directory.Delete(directory, true);
                        }
                    }
                }
                MessageBox.Show("完了");
            }
            catch (Exception ex)
            {
                MessageBox.Show("失敗 : " + ex.Message);
            }
            finally
            {
                ProgressVisibility = System.Windows.Visibility.Collapsed;
            }
        }
Exemplo n.º 35
0
        public void Password_CheckZipPassword_wi13664()
        {
            string[] passwords = { null,
                                   "Password!",
                                   TestUtilities.GenerateRandomPassword(),
                                   "_" };

            string dirToZip = Path.Combine(TopLevelDir, "zipthis");
            int subdirCount;
            int entries = TestUtilities.GenerateFilesOneLevelDeep
                (TestContext, "wi13664", dirToZip, null, out subdirCount);
            string[] filesToZip = Directory.GetFiles("zipthis", "*.*", SearchOption.AllDirectories);

            Assert.AreEqual<int>(filesToZip.Length, entries,
                                 "Incorrect number of entries in the directory.");

            for (int j = 0; j < passwords.Length; j++)
            {
                string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Password_CheckZipPassword_wi13664-{0}.zip", j));

                // Create the zip archive
                using (ZipFile zip1 = new ZipFile())
                {
                    zip1.Password = passwords[j];
                    zip1.AddFiles(filesToZip, true, "");
                    zip1.Save(zipFileToCreate);
                }

                var r = ZipFile.CheckZipPassword(zipFileToCreate, passwords[j]);
                Assert.IsTrue(r, "Bad password in round {0}", j);
            }
        }
Exemplo n.º 36
0
        public void SilentDeletion_wi10639()
        {
            string zipFileToCreate = "SilentDeletion.zip";
            string dirToZip = "dirToZip";
            string extractDir = "extracted";
            string password = TestUtilities.GenerateRandomPassword();
            string wrongPassword = "******";
            var files = TestUtilities.GenerateFilesFlat(dirToZip);

            TestContext.WriteLine("Creating the zip.");
            using (var zip = new ZipFile())
            {
                zip.Password = password;
                zip.AddFiles(files, dirToZip);
                zip.Save(zipFileToCreate);
            }

            TestContext.WriteLine("Extract one file with wrong password.");

             // pick a random entry to extract
            int ix = -1;
            string extractedFile = null;
            // perform two passes: first with correct password to extract the
            // file.  2nd with incorrect password to see if the file is
            // deleted.

            Directory.CreateDirectory(extractDir);
            for (int i=0; i < 2; i++)
            {
                try
                {
                    using (var zip = ZipFile.Read(zipFileToCreate))
                    {
                        if (i==0)
                        {
                            do
                            {
                                ix = this._rnd.Next(zip.Entries.Count);
                            }
                            while (zip[ix].IsDirectory);
                            TestContext.WriteLine("Selected entry: {0}", zip[ix].FileName);
                            extractedFile = Path.Combine(extractDir, zip[ix].FileName.Replace("/","\\"));
                            TestContext.WriteLine("name for extracted file: {0}", extractedFile);
                            Assert.IsFalse(File.Exists(extractedFile), "The file exists.");
                        }
                        TestContext.WriteLine("Cycle {0}: ExtractWithPassword()", i);
                        zip[ix].ExtractWithPassword(extractDir,
                                                    ExtractExistingFileAction.OverwriteSilently,
                                                    (i==0)? password : wrongPassword);
                    }
                }
                catch (Ionic.Zip.BadPasswordException bpe1)
                {
                    // only swallow exceptions on the first go-round
                    if (i==0) throw;
                }
                Assert.IsTrue(File.Exists(extractedFile), "Cycle {0}: The extracted file does not exist.", i);
            }
        }
Exemplo n.º 37
0
        public void ParallelDeflateStream_Create_InvalidThreshold()
        {
            string zipFileToCreate = Path.Combine(TopLevelDir, "ParallelDeflateStream_Create_InvalidThreshold.zip");
            string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var files = TestUtilities.GenerateFilesFlat(dirToZip, _rnd.Next(5) + 5, 128 * 1024 + _rnd.Next(20000));

            using (var zip = new ZipFile())
            {
                zip.ParallelDeflateThreshold = 17129;
                zip.AddFiles(files, "fodder");
                zip.Save(zipFileToCreate);
            }

            // not reached
        }