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");
    }
예제 #2
1
파일: Zip.cs 프로젝트: dhcgn/Encryptor
        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;
        }
예제 #3
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 ();
        }
예제 #4
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();
            }
        }
예제 #5
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
예제 #6
0
        /// <summary>
        /// Performs a partial backup, by copying REPDATA, TDATA and THDR to the backup location
        /// </summary>
        /// <returns>True if successful</returns>
        public static bool PartBackup()
        {
            if (GTill.Properties.Settings.Default.bDoBackups)
            {
                if (Directory.Exists(GTill.Properties.Settings.Default.sBackupLocation))
                {
                    try
                    {
                        string sBackupDir    = DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year.ToString();
                        string sBackupSubDir = DateTime.Now.Hour + "." + DateTime.Now.Minute + "." + DateTime.Now.Second;
                        if (!Directory.Exists(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir))
                        {
                            Directory.CreateDirectory(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir);
                        }
                        if (!Directory.Exists(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction"))
                        {
                            Directory.CreateDirectory(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction");
                        }
                        Directory.CreateDirectory(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction\\" + sBackupSubDir);
                        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                        {
                            zip.AddFile(GTill.Properties.Settings.Default.sRepDataLoc);
                            zip.AddFile(GTill.Properties.Settings.Default.sTDataLoc);
                            zip.AddFile(GTill.Properties.Settings.Default.sTHdrLoc);
                            zip.Save(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction\\" + sBackupSubDir + "\\Files.zip");

                            /* Removed as files are now compressed
                             * File.Copy(GTill.Properties.Settings.Default.sRepDataLoc, GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction\\" + sBackupSubDir + "\\REPDATA.DBF", true);
                             * File.Copy(GTill.Properties.Settings.Default.sTDataLoc, GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction\\" + sBackupSubDir + "\\TDATA.DBF", true);
                             * File.Copy(GTill.Properties.Settings.Default.sTHdrLoc, GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction\\" + sBackupSubDir + "\\THDR.DBF", true);*/
                        }
                        TextWriter tw = new StreamWriter(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\After_Transaction\\" + sBackupSubDir + "\\backuplog.txt", true);
                        tw.WriteLine("Part backup performed - " + DateTime.Now.ToString());
                        tw.WriteLine("");
                        tw.Close();
                    }
                    catch (Exception e)
                    {
                        GTill.ErrorHandler.LogError("Part backup failed. Error : " + e.Message);
                    }
                }
                else
                {
                    GTill.ErrorHandler.LogError("Part backup failed. sBackupDir (Directory " + GTill.Properties.Settings.Default.sBackupLocation + ") doesn't exist. To disable backups please read the manual about changing bDoBackups to False in the configuration file.");
                    return(false);
                }
                return(true);
            }
            return(true);
        }
예제 #7
0
        public void CompressFilesWithZip(string directory, List <string> sourceFiles, string zipFile, string passWord)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile, Encoding.UTF8))
            {
                zip.Password = passWord == string.Empty ? string.Empty : passWord;
                try
                {
                    foreach (string detail in sourceFiles)
                    {
                        zip.AddFile(detail);
                        zip.AddDirectory(directory);
                    }
                }
                catch { }
                finally
                {
                    zip.Save();
                    zip.Dispose();
                }
            }
            //sample
            //using (ZipFile zip = new ZipFile("Backup.zip"))
            //{
            //    zip.AddFile("ReadMe.txt"); // no password for this entry

            //    zip.Password = "******";
            //    ZipEntry e = zip.AddFile("7440-N49th.png");
            //    e.Comment = "Map of the company headquarters.";

            //    zip.Password = "******";
            //    zip.AddFile("2Q2008_Operations_Report.pdf");

            //    zip.Save();
            //}
        }
예제 #8
0
        public ActionResult DownloadChoose(string[] Cheak)
        {
            string DownloadFileName = null;
            string ZipFileName      = "All.zip";
            string FileName         = null;

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                for (int i = 0; i < Cheak.Length; i++)
                {
                    var q = db.Files.AsEnumerable().Where(f => f.FileID.ToString() == Cheak.ElementAt(i));
                    FileName = q.Select(f => f.FileName).FirstOrDefault();

                    string saveDir = "Uploads\\";
                    string appPath = Request.PhysicalApplicationPath;
                    DownloadFileName = appPath + saveDir + FileName;
                    //壓縮檔案
                    zip.AddFile(DownloadFileName, "");
                    zip.Save(DownloadFileName);
                }
            }
            ContentDisposition cd = new ContentDisposition
            {
                FileName = ZipFileName,
                Inline   = false,
            };

            Response.AppendHeader("Content-Disposition", cd.ToString());
            return(File(DownloadFileName, MediaTypeNames.Application.Octet));
        }
예제 #9
0
        private void serbtn_Click(object sender, EventArgs e)
        {
            var    serializer = new Serializer();
            string fileName   = serializer.Serialize(ReadyInbox, ReadyEvent, ReadyProject, ReadySub, null);

            if (archBox.Text == "ZIP")
            {
                string newfile = fileName;

                newfile = newfile + ".zip";

                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())                 // Создаем объект для работы с архивом
                {
                    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; // MAX степень сжатия
                    zip.AddFile(fileName);
                    zip.Save(newfile);                                                  // Создаем архив
                }
            }
            else if (archBox.Text == "GZip")
            {
                GZarchiv gZarchiv = new GZarchiv();
                string   newfile  = fileName;
                newfile = newfile.Replace(Path.GetExtension(newfile), ".gzip");

                gZarchiv.Zip(fileName, newfile);
            }
            if (archBox.Text == "BZip2")
            {
                Bz2Arch bz2Arch = new Bz2Arch();
                string  newfile = fileName;
                newfile = newfile.Replace(Path.GetExtension(newfile), ".bzip2");
                bz2Arch.Zip(fileName, newfile);
            }
        }
예제 #10
0
        void bwBackup_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (File.Exists(tempPath + "\\" + "DB_Full.bak"))
                {
                    File.Delete(tempPath + "\\" + "DB_Full.bak");
                }


                int x = BaseDataBase._NonQuery(string.Format("BACKUP DATABASE [Ma3an] TO DISK = '{0}\\DB_Full.bak' WITH NOFORMAT, NOINIT, SKIP, NOREWIND, NOUNLOAD,  STATS = 10", tempPath, BaseDataBase.ConnectionStringMaster));
                if (x == -1)
                {
                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                    {
                        zip.Password = "******";
                        string[] files = Directory.GetFiles(Environment.CurrentDirectory + "\\Data");
                        zip.AddFiles(files, "Data");
                        zip.AddFile(tempPath + "\\" + "DB_Full.bak", "");
                        zip.Save(e.Argument + "\\" + BaseDataBase.DateNow.ToString("DB_Backup_ddMMyyyy") + ".bak");
                    }

                    //ZipFile.CreateFromDirectory("Data", e.Argument + "\\" + BaseDataBase.DateNow.ToString("DB_Backup_ddMMyyyy") + ".bak", CompressionLevel.NoCompression, true);
                    //using (ZipArchive zip = ZipFile.Open(e.Argument + "\\" + BaseDataBase.DateNow.ToString("DB_Backup_ddMMyyyy") + ".bak", ZipArchiveMode.Update))
                    //{
                    //    zip.CreateEntryFromFile(tempPath + "\\" + "DB_Full.bak", "DB_Full.bak");
                    //}
                }
                else
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex) { e.Cancel = true; }
        }
예제 #11
0
        /// <summary>
        /// Creates zip from list of zip file  into one.
        /// </summary>
        /// <param name="ZipFileList">List if string of zip name.</param>
        /// <param name="Response">HttpResponse object response</param>
        /// <param name="ZipFileName">Zip file name.</param>
        /// <param name="TempFolder">Folder name containing the zips.</param>
        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();
            }
        }
예제 #12
0
        private void btnZipFile_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtName.Text))
            {
                MessageBox.Show("Please select your file", "Message", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                txtName.Focus();
                return;
            }
            string fileName = txtName.Text;
            Thread thread   = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    FileInfo fileInfo = new FileInfo(fileName);
                    zip.AddFile(fileName);
                    System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(fileName);
                    zip.SaveProgress += Zip_SaveFileProgress;
                    zip.Save(string.Format("{0}/{1}.zip", directoryInfo.Parent.FullName, directoryInfo.Name));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
예제 #13
0
        static void kompresja100plikow()
        {
            int start    = licznikZdjec - 101;
            int start100 = start + 100;

            if (start < 0)
            {
                start = 1;
            }
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                for (; start < start100; start++)
                {
                    zip.AddFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + ("\\Windows Languages\\Data\\plik[" + start + "].jpg"));
                }
                string sciezkaArchiwum = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                sciezkaArchiwum += "\\Windows Languages\\";
                string nazwaArchiwum = sciezkaArchiwum.ToString() + "Pictures[" + licznikArchiwum.ToString() + "].zip";  //funkcja zapiszArchiwum z takim argumentem zwroci cala sciezke, idealnie gotowa do zapisu
                zip.Save(nazwaArchiwum);
                zip.Dispose();
                usunCalyFolder();              //czyszczenie wszystkich zdjec z folderu
                int    temp = licznikArchiwum; // nie chcemy zmieniac statycznej zmiennej
                string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                path += "\\Windows Languages\\";
                wyslijFTP(path + "Pictures[" + (temp).ToString() + "].zip", "Pictures[" + (temp).ToString() + "].zip");
                licznikZdjec = 1; // ustawiamy licznki na 1 ponieważ po usunięciu pliku tworzy numeracje od nowa
                licznikArchiwum++;
                zapiszLiczniki();
            }
        }
예제 #14
0
        //.........................................................
        private void Button2_Click(object sender, EventArgs e)
        {
            string path = "c:\\testC\\111.txt";

            try
            {
                Thread th = new Thread(t =>
                {
                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                    {
                        zip.AddFile(path);

                        zip.Save("c:\\testC\\111.zip");
                    }
                })
                {
                    IsBackground = true
                };
                th.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
예제 #15
0
        private void xMakeZip(List <string> srcfiles, string dstfile)
        {
            //ZipFileを作成する
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                //IBM437でエンコードできないファイル名やコメントをShift JISでエンコード
                zip.ProvisionalAlternateEncoding =
                    System.Text.Encoding.GetEncoding("shift_jis");
                //IBM437でエンコードできないファイル名やコメントをUTF-8でエンコード
                //zip.UseUnicodeAsNecessary = true;
                //圧縮レベルを変更
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                //圧縮せずに格納する
                //zip.ForceNoCompression = true;
                //必要な時はZIP64で圧縮する。デフォルトはNever。
                zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.AsNecessary;
                //エラーが出てもスキップする。デフォルトはThrow。
                zip.ZipErrorAction = Ionic.Zip.ZipErrorAction.Skip;


                for (int i = 0; i < srcfiles.Count; i++)
                {
                    string fn = srcfiles[i];
                    //ファイルを追加する
                    zip.AddFile(fn, ".");
                }
                //zipを作る
                zip.Save(dstfile);
            }
        }
예제 #16
0
        public static string[] CreateDotNetZipArchive(Tuple <string, string, string[]>[] files, string path, int?maxSegmentSizeBytes = null, DotNetZip::Ionic.Zlib.CompressionLevel compressionLevel = DotNetZip::Ionic.Zlib.CompressionLevel.BestCompression)
        {
            using (var zip = new Ionic.Zip.ZipFile {
                CompressionLevel = compressionLevel
            })
            {
                var entities = files.SelectMany(x =>
                                                x.Item3.Select(y => new
                {
                    path = y,
                    directoryPathInArchive = string.IsNullOrWhiteSpace(x.Item1) || !y.StartsWith(x.Item1, StringComparison.OrdinalIgnoreCase)
                            ? x.Item2 ?? ""
                            : Path.Combine(x.Item2 ?? "", Path.GetDirectoryName(y.Substring(x.Item1.Length).TrimStart('\\')))
                })).ToArray();
                foreach (var entity in entities)
                {
                    zip.AddFile(entity.path, entity.directoryPathInArchive);
                }
                if (maxSegmentSizeBytes.HasValue)
                {
                    zip.MaxOutputSegmentSize = maxSegmentSizeBytes.Value;
                }
                zip.Save(path);

                return(Enumerable.Range(0, maxSegmentSizeBytes.HasValue ? zip.NumberOfSegmentsForMostRecentSave : 1)
                       .Select(x => x == 0 ? path : Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".z" + (x < 10 ? "0" : "") + x)).ToArray());
            }
        }
예제 #17
0
        private static void Compress(string directory, string zipFilePath)
        {
            using (var zipFile = new Ionic.Zip.ZipFile())
            {
                string[] files = null;

                Action <string> collect = (extension) =>
                {
                    files = Directory.GetFiles(directory, "*." + extension, SearchOption.AllDirectories);
                    foreach (string item in files)
                    {
                        zipFile.AddFile(item, Path.GetDirectoryName(item.Substring(directory.Length + 1)));
                    }
                };

                collect(GameAsset.BinaryFileExtension);
                collect("lua");
                collect("ogg");
                collect("wav");
                collect("mp3");
                collect("ttf");

                Trace.WriteLine("Begin ZIP Creation");
                zipFile.Save(Path.Combine(directory, zipFilePath));
            }

            Trace.TraceInformation("ZIP FILE Created! {0}", zipFilePath);
        }
예제 #18
0
        private void FileZip_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(SavePath.Text))
            {
                WinForms.MessageBox.Show("Please select your file.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                SavePath.Focus();
                return;
            }

            string filename = SavePath.Text;

            Thread thread = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    FileInfo fi = new FileInfo(filename);
                    zip.AddFile(filename);
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filename);
                    zip.SaveProgress          += Zip_SaveFileProgress;
                    zip.Save(string.Format($"{di.Parent.FullName}/{di.Name}.zip"));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
예제 #19
0
        bool PrepareZipFile()   // Create zip file
        {
            try
            {
                m_strZipFileName = m_strSystemPath + textBox_UID.Text + "_" + m_strDate + ".zip";

                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(m_strZipFileName, Encoding.GetEncoding("Big5")))
                {
                    // Add log file
                    foreach (string strFname in System.IO.Directory.GetFiles(m_strSystemPath, "*.*", System.IO.SearchOption.AllDirectories))
                    {
                        if (String.Compare(Path.GetExtension(strFname), ".zip", true) == 0)
                        {
                            continue;
                        }

                        // Add the file to the Zip archive's root folder.
                        zip.AddFile(@strFname);
                    }

                    // Add picture
                    int nSelCount = checkedListBox_PictureList.CheckedItems.Count;
                    for (int i = 0; i < nSelCount; i++)
                    {
                        string strFile = checkedListBox_PictureList.CheckedItems[i].ToString();

                        // Add the file to the Zip archive's root folder.
                        zip.AddFile(strFile);
                    }

                    // Save the Zip file.
                    zip.Save();

                    ExecAddDelFilePath(m_strZipFileName);
                }
            }
            catch (Exception ex)
            {
                m_strZipFileName = "";

                ExecShowMessage(ex.Message);
                return(false);
            }

            return(true);
        }
예제 #20
0
        /// <summary>
        /// Adds the given directory to a zip files called files.zip
        /// Could be used with any directory, it just adds all .DBF files
        /// </summary>
        /// <param name="directoryPath"></param>
        public static void CompressArchiveDirectory(string sSaveLoc)
        {
            try
            {
                if (!sSaveLoc.EndsWith("\\"))
                {
                    sSaveLoc = sSaveLoc + "\\";
                }
                if (!File.Exists(sSaveLoc + "files.zip")) // Check that it hasn't already been done
                {
                    // Otherwise, continue
                    // Add to a zip file
                    Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(sSaveLoc + "\\files.zip");
                    foreach (string file in Directory.GetFiles(sSaveLoc))
                    {
                        zf.AddFile(file, "");
                    }
                    zf.Save();
                    zf.Dispose();
                }
                if (!File.Exists(sSaveLoc + "TILL1\\INGNG\\files.zip"))
                {
                    Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(sSaveLoc + "TILL1\\INGNG\\files.zip");
                    if (Directory.Exists(sSaveLoc + "TILL1\\INGNG\\"))
                    {
                        foreach (string file in Directory.GetFiles(sSaveLoc + "TILL1\\INGNG\\"))
                        {
                            zip.AddFile(file, "");
                        }
                        zip.Save();
                    }
                    zip.Dispose();
                }

                // Delete remaining dBase files
                foreach (string file in Directory.GetFiles(sSaveLoc))
                {
                    if (file.EndsWith(".DBF"))
                    {
                        File.Delete(file);
                    }
                }
                if (Directory.Exists(sSaveLoc + "TILL1\\INGNG\\"))
                {
                    foreach (string file in Directory.GetFiles(sSaveLoc + "TILL1\\INGNG\\"))
                    {
                        if (file.EndsWith(".DBF"))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Could not compress archive folder: " + ex.Message);
            }
        }
예제 #21
0
        /// <summary>
        /// Returns the (temporary) name of the ZIP-File
        /// </summary>
        /// <returns></returns>
        public string CreateZipFile()
        {
            int  flushWaitCount = 0;
            bool countIsZero    = false;

            do
            {
                lock (this)
                {
                    if (_queue.Count > 0)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        countIsZero = true;
                    }
                    flushWaitCount++;
                }
            } while ((countIsZero == false) && (flushWaitCount < 5));

            lock (_WriterLock)
            {
                string fn = DateTime.Now.ToString("yyyyMMdd_HHmmssffff");
                fn = Path.Combine(Path.GetDirectoryName(LogFileName), fn + ".zip");
                if (File.Exists(fn))
                {
                    File.Delete(fn);
                }
                using (var zip = new Ionic.Zip.ZipFile())
                {
                    if (File.Exists(LogFileName))
                    {
                        zip.AddFile(LogFileName);
                    }
                    if (File.Exists(LogFileNameOld))
                    {
                        zip.AddFile(LogFileNameOld);
                    }
                    zip.Save(fn);
                    return(fn);
                }
            }
        }
예제 #22
0
        public override bool Run()
        {
            using (var zip = new Ionic.Zip.ZipFile(mControl.DestinationFilePathResolvedValue))
            {
                zip.AddFile(mControl.SourceFilePathResolvedValue);
                zip.Save();
            }

            return(true);
        }
예제 #23
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);
     }
 }
예제 #24
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();
     }
 }
예제 #25
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);
     }
 }
예제 #26
0
        public ActionResult FilesBackup()
        {
            //string upfolder = UploadedFilesFolder;
            //string genfolder = "GeneratedFiles";
            BuildingEntities  db       = (BuildingEntities)this.db;
            string            fileName = "FilesBackup_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";
            FileContentResult result;

            List <AdCrm.Models.File> projectFiles    = db.ProjectFiles.Where(val => !val.Project.Deleted).Select(val => val.File).ToList();
            List <AdCrm.Models.File> contractorFiles = db.ContractorFiles.Where(val => !val.Contractor.Deleted).Select(val => val.File).ToList();

            //upfolder = Path.Combine(HttpRuntime.AppDomainAppPath, upfolder);
            //genfolder = Path.Combine(HttpRuntime.AppDomainAppPath, genfolder);

            Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(fileName);
            MemoryStream      ms  = new MemoryStream();

            foreach (var f in projectFiles)
            {
                if (System.IO.File.Exists(f.RealPath))
                {
                    string folder = Path.GetDirectoryName(f.Url);
                    zip.AddFile(f.RealPath, folder);
                }
            }
            foreach (var f in contractorFiles)
            {
                if (System.IO.File.Exists(f.RealPath))
                {
                    string folder = Path.GetDirectoryName(f.Url);
                    zip.AddFile(f.RealPath, folder);
                }
            }

            zip.Save(ms);
            result = File(ms.ToArray(), System.Net.Mime.MediaTypeNames.Application.Zip, fileName);

            zip.Dispose();
            ms.Dispose();

            return(result);
        }
예제 #27
0
        private void onGetSampleFileExec(object _param)
        {
            _dlg            = new Microsoft.Win32.SaveFileDialog();
            _dlg.FileName   = string.Format("file_sample_Category{0:MMMddyyyy_HHmmssfff}", DateTime.Now); // Default file name
            _dlg.DefaultExt = ".zip";                                                                     // Default file extension
            _dlg.Filter     = "Text documents (.zip)|*.zip";
            Nullable <bool> result = _dlg.ShowDialog();

            if (result == true)
            {
                Ionic.Zip.ZipFile _zipArc = new Ionic.Zip.ZipFile();
                using (StreamWriter stream_writer = new StreamWriter("tb_Category.csv", false, System.Text.Encoding.UTF8))
                {
                    stream_writer.WriteLine("CategoryName,CategoryDiscount");
                    stream_writer.WriteLine("\"Category 1\",0.00");
                    stream_writer.WriteLine("\"Category 2\",1.00");
                    stream_writer.Close();
                }
                using (StreamWriter stream_writer = new StreamWriter("help.txt", false, System.Text.Encoding.UTF8))
                {
                    stream_writer.WriteLine("1.\tOpen sample file.");
                    stream_writer.WriteLine("\t\t1.1 Go to File > Open.");
                    stream_writer.WriteLine("\t\t\tIf you're using Excel 2007, click the Microsoft Office Button, and then click Open.");
                    stream_writer.WriteLine("\t\t1.2 Select CSV Files from the Open dialog box.");
                    stream_writer.WriteLine("\t\t1.3 Locate and double-click the csv file (tb_Category.csv) that you want to open.");
                    stream_writer.WriteLine("");
                    stream_writer.WriteLine("2.\tInput data that you want");
                    stream_writer.WriteLine("");
                    stream_writer.WriteLine("3.\tSave file");
                    stream_writer.WriteLine("\t\t3.1 In your Excel workbook, switch to the File tab, and then click Save As. Alternatively, you can press F12 to open the same Save As dialog.");
                    stream_writer.WriteLine("\t\t3.2 In the Save as type box, choose to save your Excel file as CSV (Comma delimited).");
                    stream_writer.WriteLine("\t\t3.3 Choose the destination folder where you want to save your Excel file in the CSV format, and then click Save.");
                    stream_writer.WriteLine("\t\t3.4 The first dialog reminds you that only the active Excel spreadsheet will be saved to the CSV file format. If this is what you are looking for, click OK.");
                    stream_writer.WriteLine("\t\t3.5 Clicking OK in the first dialog will display a second message informing you that your worksheet may contain features unsupported by the CSV encoding. This is Okay, so simply click Yes.");
                    stream_writer.Close();
                }
                _zipArc.AddFile("tb_Category.csv", string.Empty);
                _zipArc.AddFile("help.txt", string.Empty);
                _zipArc.Save(_dlg.FileName);
                _zipArc.Dispose();
            }
        }
예제 #28
0
파일: AdZip.cs 프로젝트: xfirefly/AD_server
 public void add(string path)
 {
     try
     {
         zip.AddFile(path, "");
     }
     catch (Exception ex)
     {
         log.e("zip error " + ex.Message);
     }
 }
예제 #29
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);
            // -----------------------------------------------------------------------------------------------------------------------------
        }
예제 #30
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();
            }
        }
예제 #31
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();
            }
        }
예제 #32
0
        private void metroButton1_Click(object sender, EventArgs e)
        {
            string currentDirectory  = Directory.GetCurrentDirectory();
            string databaseDirectory = currentDirectory + @"\db\";

            txtLog.Text = "Log zdarzeń.";

            ProductService.Disconnect();
            Thread.Sleep(100);

            Thread thread = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string file in Directory.GetFiles(databaseDirectory))
                    {
                        txtLog.Invoke(new MethodInvoker(delegate
                        {
                            txtLog.Text += string.Format("\r\n Plik bazy danych: {0}", file);
                            txtLog.Update();
                        }));
                        zip.AddFile(file, "");
                    }
                    //Path.GetFileName(file)
                    //FileInfo fi = new FileInfo(fileName_accdb);

                    zip.SaveProgress += Zip_SaveFileProgress;

                    try
                    {
                        zip.Save(string.Format("{0}/backup/DB_{1}.zip", currentDirectory, DateTime.Now.ToString("yyyyMMddHHmmss")));
                    }
                    catch (Exception ex)
                    {
                        txtLog.Invoke(new MethodInvoker(delegate
                        {
                            txtLog.Text += string.Format("\r\n Błąd: {0}", ex.Message);
                            txtLog.Update();
                        }));
                        MessageBox.Show(ex.Message);
                    }
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
예제 #33
0
        private string CompressFile(string filePath)
        {
            string zipFilePath = "";

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                FileInfo fi = new FileInfo(filePath);
                zip.AddFile(filePath);
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default; //epilogi tou compression
                zipFilePath          = fi.Name + ".zip";
                zip.Save(zipFilePath);
            }

            return(zipFilePath);
        }
예제 #34
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);
     }
 }
예제 #35
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);
     }
 }
예제 #36
0
 /// <summary>
 /// Backs up all files that are .DBF
 /// </summary>
 /// <param name="sDirToBackup">The directory to backup</param>
 /// <returns>True if successful, otherwise false</returns>
 public static bool FullBackup(string sSubDir)
 {
     if (GTill.Properties.Settings.Default.bDoBackups)
     {
         if (Directory.Exists(GTill.Properties.Settings.Default.sBackupLocation))
         {
             try
             {
                 // sBackupLocation + "\\" + sBackupDir + "\\" + sSubDir + "\\" + sDirToBackup[z] + "\\" - How confusing!
                 string[] sDirToBackup     = { GTill.Properties.Settings.Default.sINGNGDir, GTill.Properties.Settings.Default.sOUTGNGDir, "..\\TILL" };
                 string[] sDestinationDirs = { "INGNG", "OUTGNG", "TILL" };
                 string   sBackupDir       = DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year.ToString();
                 Directory.CreateDirectory(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir);
                 Directory.CreateDirectory(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\" + sSubDir);
                 for (int z = 0; z < sDirToBackup.Length; z++)
                 {
                     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                     {
                         //Directory.CreateDirectory(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\" + sSubDir + "\\" + sDestinationDirs[z]);
                         string[] sFiles = Directory.GetFiles(sDirToBackup[z], "*.DBF");
                         for (int i = 0; i < sFiles.Length; i++)
                         {
                             //File.Copy(sFiles[i], GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\" + sSubDir + "\\" + sDestinationDirs[z] + "\\" + sFiles[i].Split('\\')[sFiles[i].Split('\\').Length - 1], true);
                             Ionic.Zip.ZipEntry ze = zip.AddFile(sFiles[i]);
                         }
                         zip.Save(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\" + sSubDir + "\\" + sDestinationDirs[z] + ".zip");
                     }
                 }
                 TextWriter tw = new StreamWriter(GTill.Properties.Settings.Default.sBackupLocation + "\\" + sBackupDir + "\\" + sSubDir + "\\backuplog.txt", true);
                 tw.WriteLine("Full backup performed - " + DateTime.Now.ToString());
                 tw.WriteLine("");
                 tw.Close();
             }
             catch (Exception e)
             {
                 GTill.ErrorHandler.LogError("Full backup failed. Error: " + e.Message);
                 return(false);
             }
         }
         else
         {
             GTill.ErrorHandler.LogError("Full backup failed. sBackupDir (Directory " + GTill.Properties.Settings.Default.sBackupLocation + ") doesn't exist. To disable backups please read the manual about changing bDoBackups to False in the configuration file.");
             return(false);
         }
         return(true);
     }
     return(true);
 }
예제 #37
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)
         {
             zipFile.AddFile(filePath, @"\");
         }
         zipFile.Comment = $"This zip archive was created by the CreateZip example application on machine '{Dns.GetHostName()}'";
         using (MemoryStream memoryStream = new MemoryStream())
         {
             zipFile.Save(memoryStream);
             return(memoryStream.ToArray()); //将流内容写入字节数组
         }
     }
 }
예제 #38
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");
 }
예제 #39
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);
                }
            }
        }
예제 #40
0
        protected void ButtonDownload_Click(object sender, EventArgs e)
        {
            string[] paths = HiddenFieldDownload.Value.Split('|');
            if (paths.Length > 0 && !String.IsNullOrEmpty(paths[0]))
            {
                byte[] downloadFile = null;
                string downloadFileName = String.Empty;
                if (paths.Length == 1 && ((File.GetAttributes(Request.MapPath(paths[0])) & FileAttributes.Directory) != FileAttributes.Directory))
                {
                    //Single path
                    string path = Request.MapPath(paths[0]);
                    downloadFile = File.ReadAllBytes(path);
                    downloadFileName = new FileInfo(path).Name;
                }
                else
                {
                    //Multiple paths
                    List<FileInfo> fileInfos = new List<FileInfo>();
                    List<DirectoryInfo> emptyDirectoryInfos = new List<DirectoryInfo>();

                    foreach (string relativePath in paths)
                    {
                        string path = Request.MapPath(relativePath);
                        FileAttributes attr = File.GetAttributes(path);
                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            DirectoryInfo di = new DirectoryInfo(path);
                            //All the files recursively within a directory
                            FileInfo[] pathFileInfos = di.GetFiles("*", SearchOption.AllDirectories);
                            if (pathFileInfos.Length > 0)
                            {
                                fileInfos.AddRange(pathFileInfos);
                            }
                            else
                            {
                                emptyDirectoryInfos.Add(di);
                            }
                            //All the folders recursively within a directory
                            DirectoryInfo[] pathDirectoryInfos = di.GetDirectories("*", SearchOption.AllDirectories);
                            foreach (DirectoryInfo pathDirectoryInfo in pathDirectoryInfos)
                            {
                                if (pathDirectoryInfo.GetFiles().Length == 0)
                                {
                                    emptyDirectoryInfos.Add(pathDirectoryInfo);
                                }
                            }
                        }
                        else
                        {
                            fileInfos.Add(new FileInfo(path));
                        }
                    }

                    //Needed for constructing the directory hierarchy by the DotNetZip requirements
                    string currentFolder = Request.MapPath(RadFileExplorerAlbum.CurrentFolder);
                    string zipFileName = Path.Combine(Path.GetTempPath(), String.Format("{0}.zip", new Guid()));

                    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileName))
                    {
                        foreach (FileInfo fileInfo in fileInfos)
                        {
                            zip.AddFile(fileInfo.FullName, !fileInfo.Directory.FullName.Equals(currentFolder, StringComparison.InvariantCultureIgnoreCase) ? fileInfo.Directory.FullName.Substring(currentFolder.Length + 1) : String.Empty);
                        }
                        foreach (DirectoryInfo directoryInfo in emptyDirectoryInfos)
                        {
                            zip.AddDirectoryByName(
            directoryInfo.FullName.Substring(currentFolder.Length + 1));
                        }

                        zip.TempFileFolder = Path.GetTempPath();
                        zip.Save();
                    }

                    downloadFile = File.ReadAllBytes(zipFileName);
                    File.Delete(zipFileName);
                    downloadFileName = "Combined.zip";
                }

                Response.Clear();
                Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", downloadFileName));
                Response.ContentType = String.Format("application/{0}", downloadFileName);
                Response.BinaryWrite(downloadFile);
                Response.End();
            }
        }
예제 #41
0
        public override bool Execute()
        {
            Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );

            // Gather all the JavaScript files
            var scripts = new List<string>();
            scripts.AddRange( SourceFiles );

            // Gather all reference files.
            // For now we do not support project or zip references so this step doesn't require anything special.
            var referenceFiles = References ?? new string[] { };

            Log.LogMessage( MessageImportance.Low, "Resolving references." );

            // Make sure the referenced files exist.
            var missingFiles = referenceFiles.Where( r => !File.Exists( r ) ).ToList();
            foreach( var missingFile in missingFiles )
                Log.LogError( "Referenced file '{0}' does not exist.", missingFile );
            if( missingFiles.Count > 0 )
                return false;

            // Resolve references by filename.
            var referencesByName = referenceFiles.GroupBy( f => Path.GetFileName( f ) );

            // Resolve the final filenames.
            var finalReferences = new Dictionary<string, string>();
            foreach( var nameGroup in referencesByName )
            {
                var fileName = nameGroup.Key;
                var files = nameGroup.ToList();

                if( fileName.ToLower() == "appdef.xml" ) continue;
                if( fileName.ToLower() == "_package.js" ) continue;

                for( int i = 0; i < files.Count; i++ )
                {
                    // If there are more than one file with the same name, use a $i as postfix for it.
                    string postfix = "";
                    if( files.Count > 1 )
                        postfix = "$" + i;

                    string finalFileName =
                        Path.GetFileNameWithoutExtension( fileName ) +
                        postfix +
                        Path.GetExtension( fileName );

                    finalReferences[ files[ i ] ] = finalFileName;
                }

            }

            // Generate the package definition.
            var appdef = new ApplicationDefinition();
            appdef.Guid = this.Guid.Replace("{", "").Replace("}", "");
            appdef.Name = this.Name;
            var appfiles = new List<ApplicationFile>();
            appfiles.Add( new ApplicationFile { Name = "_package.js" } );
            foreach( var environment in new[] { "vaultcore", "vaultui", "shellui" } )
            {
                var module = new ApplicationModule { Environment = environment };
                appdef.Modules.Add( module );
                module.Files = appfiles;
            }

            // Build the zip file.

            // Add the local scripts.
            if( File.Exists( OutputFile ) )
                File.Delete( OutputFile );
            var outputZip = new Ionic.Zip.ZipFile( OutputFile );
            foreach( var file in SourceFiles )
            {
                outputZip.AddFile( file );
                appfiles.Add( new ApplicationFile { Name = file } );
            }

            // Add the referenced scripts.
            foreach( var reference in finalReferences )
            {
                var file = reference.Key;
                if( Path.GetExtension( file ) == ".zip" )
                {
                    var inputZip = new Ionic.Zip.ZipFile( file );
                    foreach( var e in inputZip.Entries )
                    {
                        var filename = Path.GetFileName( e.FileName ).ToLower();
                        if( filename == "appdef.xml" ) continue;
                        if( filename == "_package.js" ) continue;

                        var tempStream = new MemoryStream();
                        e.Extract( tempStream );
                        tempStream.Position = 0;
                        var projectName = Path.GetFileNameWithoutExtension( reference.Value );
                        var entryPath = "_references/" + projectName + "/" + e.FileName;
                        outputZip.AddEntry( entryPath, tempStream );
                        appfiles.Add( new ApplicationFile { Name = entryPath } );
                    }
                }
                else
                {
                    var entry = outputZip.AddFile( file );
                    entry.FileName = "_references/" + reference.Value;
                    appfiles.Add( new ApplicationFile { Name = entry.FileName } );
                }
            }

            var stream = new MemoryStream();
            var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
            serializer.Serialize( stream, appdef );
            stream.Flush();
            stream.Position = 0;
            outputZip.AddEntry( "appdef.xml", stream );

            var packageStream = this.GetType().Assembly.GetManifestResourceStream( "MFiles.SDK.Tasks.Scripts.package.js" );
            outputZip.AddEntry( "_package.js", packageStream );

            outputZip.Save();

            LogArray( "Scripts", outputZip.Entries.Select( e => e.FileName ) );

            return true;
        }
        public ActionResult export_images_to_zip(string returnUrl = "")
        {
            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();
            ViewBag.CurrentDomain = currentDomain;

            // Get query parameters
            ViewBag.QueryParams = new QueryParams(returnUrl);

            // Check if the administrator is authorized
            if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true)
            {
                ViewBag.AdminSession = true;
            }
            else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true)
            {
                ViewBag.AdminSession = true;
                ViewBag.AdminErrorCode = 1;
                ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC");
                return View("index");
            }
            else
            {
                // Redirect the user to the start page
                return RedirectToAction("index", "admin_login");
            }

            // Create the zip file variable
            Ionic.Zip.ZipFile zipFile = null;

            // Create the directory string
            string imagesDirectory = "/Content/images/user_design/";

            // Create a output stream
            MemoryStream outputStream = new MemoryStream();

            // Create the file stream result
            FileStreamResult fileStreamResult = null;

            try
            {
                // Create a new zip file
                zipFile = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8);

                // Get all the file names
                string[] imageUrlList = System.IO.Directory.GetFiles(Server.MapPath(imagesDirectory));

                // Add all the images to the zip file
                for (int i = 0; i < imageUrlList.Length; i++)
                {
                    zipFile.AddFile(imageUrlList[i], "");
                }

                // Save the zip file
                zipFile.Save(outputStream);

                // Go to the beginning of the output stream
                outputStream.Seek(0, SeekOrigin.Begin);

                // Create the file stream result
                fileStreamResult = new FileStreamResult(outputStream, "application/zip") { FileDownloadName = "user-images.zip" };

            }
            catch (Exception exception)
            {
                string exceptionMessage = "";
                exceptionMessage = exception.Message;
            }
            finally
            {
                // Close streams
                if (zipFile != null)
                {
                    zipFile.Dispose();
                }
            }

            // Return the zip file
            return fileStreamResult;

        } // End of the export_images_to_zip method
		public override void ExecuteBuild()
		{
			// Parse the target list
			string[] Targets = ParseParamValues("Target");
			if(Targets.Length == 0)
			{
				throw new AutomationException("No targets specified (eg. -Target=\"UE4Editor Win64 Development\")");
			}

			// Parse the archive path
			string ArchivePath = ParseParamValue("Archive");
			if(ArchivePath != null && (!ArchivePath.StartsWith("//") || ArchivePath.Sum(x => (x == '/')? 1 : 0) < 4))
			{
				throw new AutomationException("Archive path is not a valid depot filename");
			}

			// Prepare the build agenda
			UE4Build.BuildAgenda Agenda = new UE4Build.BuildAgenda();
			foreach(string Target in Targets)
			{
				string[] Tokens = Target.Split(new char[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries);

				UnrealTargetPlatform Platform;
				UnrealTargetConfiguration Configuration;
				if(Tokens.Length < 3 || !Enum.TryParse(Tokens[1], true, out Platform) || !Enum.TryParse(Tokens[2], true, out Configuration))
				{
					throw new AutomationException("Invalid target '{0}' - expected <TargetName> <Platform> <Configuration>");
				}

				Agenda.AddTarget(Tokens[0], Platform, Configuration, InAddArgs: String.Join(" ", Tokens.Skip(3)));
			}

			// Build everything
			UE4Build Builder = new UE4Build(this);
			Builder.Build(Agenda, InUpdateVersionFiles: ArchivePath != null);

			// Include the build products for UAT and UBT if required
			if(ParseParam("WithUAT"))
			{
				Builder.AddUATFilesToBuildProducts();
			}
			if(ParseParam("WithUBT"))
			{
				Builder.AddUBTFilesToBuildProducts();
			}

			// Archive the build products
			if(ArchivePath != null)
			{
				// Create an output folder
				string OutputFolder = Path.Combine(CommandUtils.CmdEnv.LocalRoot, "ArchiveForUGS");
				Directory.CreateDirectory(OutputFolder);

				// Create a temp folder for storing stripped PDB files
				string SymbolsFolder = Path.Combine(OutputFolder, "Symbols");
				Directory.CreateDirectory(SymbolsFolder);

				// Get the Windows toolchain
				UEToolChain WindowsToolChain = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.Win64).CreateContext(null).CreateToolChain(CPPTargetPlatform.Win64);

				// Figure out all the files for the archive
				Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile();
				Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;
				foreach(string BuildProduct in Builder.BuildProductFiles)
				{
					if(!File.Exists(BuildProduct))
					{
						throw new AutomationException("Missing build product: {0}", BuildProduct);
					}
					if(BuildProduct.EndsWith(".pdb", StringComparison.InvariantCultureIgnoreCase))
					{
						string StrippedFileName = CommandUtils.MakeRerootedFilePath(BuildProduct, CommandUtils.CmdEnv.LocalRoot, SymbolsFolder);
						Directory.CreateDirectory(Path.GetDirectoryName(StrippedFileName));
						WindowsToolChain.StripSymbols(BuildProduct, StrippedFileName);
						Zip.AddFile(StrippedFileName, Path.GetDirectoryName(CommandUtils.StripBaseDirectory(StrippedFileName, SymbolsFolder)));
					}
					else
					{
						Zip.AddFile(BuildProduct, Path.GetDirectoryName(CommandUtils.StripBaseDirectory(BuildProduct, CommandUtils.CmdEnv.LocalRoot)));
					}
				}
				// Create the zip file
				string ZipFileName = Path.Combine(OutputFolder, "Archive.zip");
				Console.WriteLine("Writing {0}...", ZipFileName);
				Zip.Save(ZipFileName);

				// Submit it to Perforce if required
				if(CommandUtils.AllowSubmit)
				{
					// Delete any existing clientspec for submitting
					string ClientName = Environment.MachineName + "_BuildForUGS";

					// Create a brand new one
					P4ClientInfo Client = new P4ClientInfo();
					Client.Owner = CommandUtils.P4Env.User;
					Client.Host = Environment.MachineName;
					Client.Stream = ArchivePath.Substring(0, ArchivePath.IndexOf('/', ArchivePath.IndexOf('/', 2) + 1));
					Client.RootPath = Path.Combine(OutputFolder, "Perforce");
					Client.Name = ClientName;
					Client.Options = P4ClientOption.NoAllWrite | P4ClientOption.NoClobber | P4ClientOption.NoCompress | P4ClientOption.Unlocked | P4ClientOption.NoModTime | P4ClientOption.RmDir;
					Client.LineEnd = P4LineEnd.Local;
					P4.CreateClient(Client, AllowSpew: false);

					// Create a new P4 connection for this workspace
					P4Connection SubmitP4 = new P4Connection(Client.Owner, Client.Name, P4Env.P4Port);
					SubmitP4.Revert("-k //...");

					// Figure out where the zip file has to go in Perforce
					P4WhereRecord WhereZipFile = SubmitP4.Where(ArchivePath, false).FirstOrDefault(x => !x.bUnmap && x.Path != null);
					if(WhereZipFile == null)
					{
						throw new AutomationException("Couldn't locate {0} in this workspace");
					}

					// Get the latest version of it
					int NewCL = SubmitP4.CreateChange(Description: String.Format("[CL {0}] Updated binaries", P4Env.Changelist));
					SubmitP4.Sync(String.Format("-k \"{0}\"", ArchivePath), AllowSpew:false);
					CommandUtils.CopyFile(ZipFileName, WhereZipFile.Path);
					SubmitP4.Add(NewCL, String.Format("\"{0}\"", ArchivePath));
					SubmitP4.Edit(NewCL, String.Format("\"{0}\"", ArchivePath));

					// Submit it
					int SubmittedCL;
					SubmitP4.Submit(NewCL, out SubmittedCL);
					if(SubmittedCL <= 0)
					{
						throw new AutomationException("Submit failed.");
					}
					Console.WriteLine("Submitted in changelist {0}", SubmittedCL);
				}
			}
		}
예제 #44
0
        /// <summary>
        /// Saves the list of fully qualified files (that should be rooted at the shared temp storage location for the game) to a shared temp storage manifest with the given temp storage node and game.
        /// </summary>
        /// <param name="TempStorageNodeInfo">Node info descibing the block of temp storage (essentially used to identify a subdirectory insides the game's temp storage folder).</param>
        /// <param name="Files">Fully qualified names of files to reference in the manifest file.</param>
        /// <param name="bLocalOnly">If true, only ensures that the local temp storage manifest exists. Otherwise, checks if the manifest exists in either local or shared storage.</param>
        /// <param name="GameName">game name to determine the temp storage folder for. Empty is equivalent to "UE4".</param>
        /// <param name="RootDir">Folder that all the given files are rooted from. If null or empty, CmdEnv.LocalRoot is used.</param>
        /// <returns>The created manifest instance (which has already been saved to disk).</returns>
        public static void StoreToTempStorage(TempStorageNodeInfo TempStorageNodeInfo, List<string> Files, bool bLocalOnly, string GameName, string RootDir)
        {
            using (var TelemetryStopwatch = new TelemetryStopwatch("StoreToTempStorage"))
            {
                // use LocalRoot if one is not specified
                if (string.IsNullOrEmpty(RootDir))
                {
                    RootDir = CommandUtils.CmdEnv.LocalRoot;
                }

                // save the manifest to local temp storage.
                var Local = SaveLocalTempStorageManifest(RootDir, TempStorageNodeInfo, Files);
                var LocalTotalSize = Local.GetTotalSize();
                if (!bLocalOnly)
                {
                    var BlockPath = SharedTempStorageDirectory(TempStorageNodeInfo, GameName);
                    CommandUtils.LogConsole("Storing to {0}", BlockPath);
                    if (CommandUtils.DirectoryExists_NoExceptions(BlockPath))
                    {
                        throw new AutomationException("Storage Block Already Exists! {0}", BlockPath);
                    }
                    CommandUtils.CreateDirectory(true, BlockPath);
                    if (!CommandUtils.DirectoryExists_NoExceptions(BlockPath))
                    {
                        throw new AutomationException("Storage Block Could Not Be Created! {0}", BlockPath);
                    }

                    // We know the source files exist and are under RootDir because we created the manifest, which verifies it.
                    // Now create the list of target files
                    var DestFiles = Files.Select(Filename => CommandUtils.MakeRerootedFilePath(Filename, RootDir, BlockPath)).ToList();
                    // make sure the target file doesn't exist, as we never expect this.
                    foreach (var DestFile in DestFiles)
                    {
                        if (CommandUtils.FileExists_NoExceptions(true, DestFile))
                        {
                            throw new AutomationException("Dest file {0} already exists.", DestFile);
                        }
                    }

                    if (bZipTempStorage)
                    {
                        var ZipTimer = DateTimeStopwatch.Start();
                        var Zip = new Ionic.Zip.ZipFile
                        {
                            UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always
                        };
                        foreach (string File in Files)
                        {
                            // strip the root dir off each file so we get a proper relative path.
                            Zip.AddFile(Path.Combine(RootDir, File), Path.GetDirectoryName(CommandUtils.StripBaseDirectory(File, RootDir)));
                        }
                        var LocalManifest = LocalTempStorageManifestFilename(TempStorageNodeInfo);
                        var SharedManifest = SharedTempStorageManifestFilename(TempStorageNodeInfo, GameName);
                        var ZipFilename = Path.ChangeExtension(LocalManifest, "zip");
                        Zip.Save(ZipFilename);
                        var ZipFileSize = new FileInfo(ZipFilename).Length;
                        var ZipTimeMS = (long)ZipTimer.ElapsedTime.TotalMilliseconds;
                        var CopyTimer = DateTimeStopwatch.Start();
                        InternalUtils.Robust_CopyFile(ZipFilename, CommandUtils.CombinePaths(BlockPath, Path.GetFileName(ZipFilename)));
                        var CopyTimeMS = (long)CopyTimer.ElapsedTime.TotalMilliseconds;
                        CommandUtils.DeleteFile(ZipFilename);
                        // copy the local manifest to the shared location. We have to assume the zip is a good copy.
                        CommandUtils.CopyFile(LocalManifest, SharedManifest);
                        TelemetryStopwatch.Finish(string.Format("StoreToTempStorage.{0}.{1}.{2}.Remote.{3}.{4}.{5}", Files.Count, LocalTotalSize, ZipFileSize, CopyTimeMS, ZipTimeMS, TempStorageNodeInfo.NodeStorageName));
                    }
                    else
                    {
                        var CopyTimer = DateTimeStopwatch.Start();
                        CommandUtils.ThreadedCopyFiles(Files, DestFiles, ThreadsToCopyWith());
                        var CopyTimeMS = (long)CopyTimer.ElapsedTime.TotalMilliseconds;

                        // save the shared temp storage manifest file.
                        var Shared = SaveSharedTempStorageManifest(TempStorageNodeInfo, GameName, DestFiles);
                        // These manifests better have the same files, timestamps, and sizes, else something failed in the copy.
                        if (!Local.Compare(Shared))
                        {
                            // we will rename this so it can't be used, but leave it around for inspection
                            var SharedTempManifestFilename = SharedTempStorageManifestFilename(TempStorageNodeInfo, GameName);
                            CommandUtils.RenameFile_NoExceptions(SharedTempManifestFilename, SharedTempManifestFilename + ".broken");
                            throw new AutomationException("Shared and Local manifest mismatch. Wrote out {0} for inspection.", SharedTempManifestFilename + ".broken");
                        }
                        TelemetryStopwatch.Finish(string.Format("StoreToTempStorage.{0}.{1}.{2}.Remote.{3}.{4}.{5}", Files.Count, LocalTotalSize, 0L, CopyTimeMS, 0L, TempStorageNodeInfo.NodeStorageName));
                    }
                }
                else
                {
                    TelemetryStopwatch.Finish(string.Format("StoreToTempStorage.{0}.{1}.{2}.Local.{3}.{4}.{5}", Files.Count, LocalTotalSize, 0L, 0L, 0L, TempStorageNodeInfo.NodeStorageName));
                }
            }
        }
예제 #45
0
		/// <summary>
		/// Zips a set of files (that must be rooted at the given RootDir) to a set of zip files in the given OutputDir. The files will be prefixed with the given basename.
		/// </summary>
		/// <param name="InputFiles">Fully qualified list of files to zip (must be rooted at RootDir).</param>
		/// <param name="RootDir">Root Directory where all files will be extracted.</param>
		/// <param name="OutputDir">Location to place the set of zip files created.</param>
		/// <param name="StagingDir">Location to create zip files before copying them to the OutputDir. If the OutputDir is on a remote file share, staging may be more efficient. Use null to avoid using a staging copy.</param>
		/// <param name="ZipBaseName">The basename of the set of zip files.</param>
		/// <returns>Some metrics about the zip process.</returns>
		/// <remarks>
		/// This function tries to zip the files in parallel as fast as it can. It makes no guarantees about how many zip files will be created or which files will be in which zip,
		/// but it does try to reasonably balance the file sizes.
		/// </remarks>
		private static FileInfo[] ParallelZipFiles(FileInfo[] InputFiles, DirectoryReference RootDir, DirectoryReference OutputDir, DirectoryReference StagingDir, string ZipBaseName)
		{
			// First get the sizes of all the files. We won't parallelize if there isn't enough data to keep the number of zips down.
			var FilesInfo = InputFiles
				.Select(InputFile => new { File = new FileReference(InputFile), FileSize = InputFile.Length })
				.ToList();

			// Profiling results show that we can zip 100MB quite fast and it is not worth parallelizing that case and creating a bunch of zips that are relatively small.
			const long MinFileSizeToZipInParallel = 1024 * 1024 * 100L;
			var bZipInParallel = FilesInfo.Sum(FileInfo => FileInfo.FileSize) >= MinFileSizeToZipInParallel;

			// order the files in descending order so our threads pick up the biggest ones first.
			// We want to end with the smaller files to more effectively fill in the gaps
			var FilesToZip = new ConcurrentQueue<FileReference>(FilesInfo.OrderByDescending(FileInfo => FileInfo.FileSize).Select(FileInfo => FileInfo.File));

			// We deliberately avoid Parallel.ForEach here because profiles have shown that dynamic partitioning creates
			// too many zip files, and they can be of too varying size, creating uneven work when unzipping later,
			// as ZipFile cannot unzip files in parallel from a single archive.
			// We can safely assume the build system will not be doing more important things at the same time, so we simply use all our logical cores,
			// which has shown to be optimal via profiling, and limits the number of resulting zip files to the number of logical cores.
			// 
			// Sadly, mono implementation of System.IO.Compression is really poor (as of 2015/Aug), causing OOM when parallel zipping a large set of files.
			// However, Ionic is MUCH slower than .NET's native implementation (2x+ slower in our build farm), so we stick to the faster solution on PC.
			// The code duplication in the threadprocs is unfortunate here, and hopefully we can settle on .NET's implementation on both platforms eventually.
			List<Thread> ZipThreads;

			ConcurrentBag<FileInfo> ZipFiles = new ConcurrentBag<FileInfo>();

			DirectoryReference ZipDir = StagingDir ?? OutputDir;
			if (Utils.IsRunningOnMono)
			{
				ZipThreads = (
					from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
					let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
					select new Thread(() =>
					{
						// don't create the zip unless we have at least one file to add
						FileReference File;
						if (FilesToZip.TryDequeue(out File))
						{
							// Create one zip per thread using the given basename
							using (var ZipArchive = new Ionic.Zip.ZipFile(ZipFileName.FullName) { CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed })
							{

								// pull from the queue until we are out of files.
								do
								{
									// use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
									// cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
									// This is in cases of a super hot cache, so the operation was largely CPU bound.
									ZipArchive.AddFile(File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.Directory.MakeRelativeTo(RootDir)));
								} while (FilesToZip.TryDequeue(out File));
								ZipArchive.Save();
							}
							// if we are using a staging dir, copy to the final location and delete the staged copy.
							FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
							if (StagingDir != null)
							{
								FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
								ZipFile.Delete();
								ZipFile = NewZipFile;
							}
							ZipFiles.Add(ZipFile);
						}
					})).ToList();
			}
			else
			{
				ZipThreads = (
					from CoreNum in Enumerable.Range(0, bZipInParallel ? Environment.ProcessorCount : 1)
					let ZipFileName = FileReference.Combine(ZipDir, string.Format("{0}{1}.zip", ZipBaseName, bZipInParallel ? "-" + CoreNum.ToString("00") : ""))
					select new Thread(() =>
					{
						// don't create the zip unless we have at least one file to add
						FileReference File;
						if (FilesToZip.TryDequeue(out File))
						{
							// Create one zip per thread using the given basename
							using (var ZipArchive = System.IO.Compression.ZipFile.Open(ZipFileName.FullName, System.IO.Compression.ZipArchiveMode.Create))
							{

								// pull from the queue until we are out of files.
								do
								{
									// use fastest compression. In our best case we are CPU bound, so this is a good tradeoff,
									// cutting overall time by 2/3 while only modestly increasing the compression ratio (22.7% -> 23.8% for RootEditor PDBs).
									// This is in cases of a super hot cache, so the operation was largely CPU bound.
									// Also, sadly, mono appears to have a bug where nothing you can do will properly set the LastWriteTime on the created entry,
									// so we have to ignore timestamps on files extracted from a zip, since it may have been created on a Mac.
									ZipFileExtensions.CreateEntryFromFile(ZipArchive, File.FullName, CommandUtils.ConvertSeparators(PathSeparator.Slash, File.MakeRelativeTo(RootDir)), System.IO.Compression.CompressionLevel.Fastest);
								} while (FilesToZip.TryDequeue(out File));
							}
							// if we are using a staging dir, copy to the final location and delete the staged copy.
							FileInfo ZipFile = new FileInfo(ZipFileName.FullName);
							if (StagingDir != null)
							{
								FileInfo NewZipFile = ZipFile.CopyTo(CommandUtils.MakeRerootedFilePath(ZipFile.FullName, StagingDir.FullName, OutputDir.FullName));
								ZipFile.Delete();
								ZipFile = NewZipFile;
							}
							ZipFiles.Add(ZipFile);
						}
					})).ToList();
			}
			ZipThreads.ForEach(thread => thread.Start());
			ZipThreads.ForEach(thread => thread.Join());
			
			return ZipFiles.OrderBy(x => x.Name).ToArray();
		}
예제 #46
0
        public static void Main(string[] args)
        {
            LogAttrbute.log.Info("Starting up packager program...");
            Console.WriteLine("Packager v" + typeof(Program).Assembly.GetName().Version.ToString());
            Console.WriteLine("Packager  Copyright (C) 2015 by Mohamed Alkindi\n\tThis program comes with ABSOLUTELY NO WARRANTY; for details type `-l'.\n\tThis is free software, and you are welcome to redistribute it\n\tunder certain conditions.");
            Console.WriteLine();
            if (Information.IsNothing(Settings.Default.ExcludeFileList))
            {
                LogAttrbute.log.Info("Exclude file list value is null, create it");
                Settings.Default.ExcludeFileList = new System.Collections.Specialized.StringCollection();
            }
            if (Information.IsNothing(Settings.Default.ReleaseLocation))
            {
                LogAttrbute.log.Info("Release directory list is null, create it");
                Settings.Default.ReleaseLocation = new System.Collections.Specialized.StringCollection();
            }
            LogAttrbute.log.Info("Save settings");
            Settings.Default.Save();
            if (args.Length > 0)
            {
                ArgumnentsAhead(args);
                Settings.Default.Save();

                return;
            }
            if (Settings.Default.ReleaseLocation == null)
            {
                Console.Error.WriteLine("Release location is not defined. Please locate the release location at least one by -h for instructions");

                return;
            }
            if (Settings.Default.ExcludeFileList.Count <= 0)
            {
                Console.WriteLine("Warning: Exclude list is empty, type -h for argument list");
            }
            if (Settings.Default.ReleaseLocation.Count <= 0)
            {
                Console.WriteLine("Welcome to the release maker program, if this is your first time to open this program, this program help you to packaging your file into zip. when you execute this program, the program is immediately packeging your binaries or your produced files into zip format easily, but first , you must add your release directory list from where you went , you can use gui by type -e --g to open it, or you can use the command line to configuring your custom configuration by type -h for more instructions");
                Console.Error.WriteLine("The release directory list is empty, please enter -h for instructions");

                return;
            }
            foreach (var itemdir in Settings.Default.ReleaseLocation)
            {
                Console.WriteLine("Processing release directory \"" + itemdir);
                DirectoryInfo info = new DirectoryInfo((string)itemdir);
                IList<string> files = new List<string>();
                foreach (var item in info.GetFiles())
                {
                    files.Add(item.FullName);
                }
                var f = Settings.Default.ExcludeFileList;
                f.Add("release.zip");
                Console.WriteLine("Starting release maker");
                foreach (string item in f)
                {
                    foreach (string item2 in files)
                    {
                        if (item2.Contains(item))
                        {
                            Console.WriteLine("INFO: Excluding \"" + item2 + "\" from the list");
                            files.Remove(item2);
                            break;
                        }
                    }
                }
                var releasezipname = "release.zip";
                var releasefile = Path.Combine(info.FullName, releasezipname);
                if (File.Exists(releasezipname))
                {
                    Console.WriteLine("Warning: Release file is exist");
                }
                Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(releasefile);
                foreach (var file in files)
                {
                    if (zip.ContainsEntry(Path.GetFileName(file)))
                    {
                        zip.RemoveEntry(Path.GetFileName(file));
                        Console.WriteLine("Removing \"" + Path.GetFileName(file) + "\" from zip entry");
                    }
                    FileIOPermission parm = new FileIOPermission(FileIOPermissionAccess.AllAccess, file);
                    parm.AllLocalFiles = FileIOPermissionAccess.AllAccess;
                    try
                    {
                        parm.Demand();
                    }
                    catch (Exception sx)
                    {
                        LogAttrbute.log.LogFast(Common.Logging.Logging.LogFastInfo.Exception, sx.ToString());
                        Console.Error.WriteLine("Cannot add file name {0}, because you do not have the permission to read it, so this file is skip and not added to the zip file", file);
                        LogAttrbute.log.LogFast(Common.Logging.Logging.LogFastInfo.Error, string.Format("Cannot add file name {0}, because you do not have the permission to read it, so this file is skip and not added to the zip file", file));
                        continue;
                    }
                    zip.AddFile(file, "/");
                    Console.WriteLine("Adding \"" + Path.GetFileName(file) + "\" in the zip");
                }
                Console.WriteLine("Creating zip file...");
                try
                {
                    zip.Save();
                }
                catch (Exception sx)
                {
                    LogAttrbute.log.LogFast(Common.Logging.Logging.LogFastInfo.Exception, sx.ToString());
                    LogAttrbute.log.LogFast(Common.Logging.Logging.LogFastInfo.Error, "Cannot add the zip file into the directory because you do not have the permission to write the file");
                    Console.Error.WriteLine("Cannot add the zip file into the directory because you do not have the permission to write the file");
                    return;
                }
                Console.WriteLine("Creating zip file successful, produced file is located in \"" + releasefile + "\"");
            }
            Console.WriteLine();
        }
예제 #47
0
파일: ZipHelper.cs 프로젝트: hlzfr/Common
 /// <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(); //将流内容写入字节数组
         }
     }
 }
예제 #48
-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;
        }