AddFile() public method

Adds a File to a Zip file archive.

This call collects metadata for the named file in the filesystem, including the file attributes and the timestamp, and inserts that metadata into the resulting ZipEntry. Only when the application calls Save() on the ZipFile, does DotNetZip read the file from the filesystem and then write the content to the zip file archive.

This method will throw an exception if an entry with the same name already exists in the ZipFile.

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

public AddFile ( string fileName ) : ZipEntry
fileName string /// The name of the file to add. It should refer to a file in the filesystem. /// The name of the file may be a relative path or a fully-qualified path. ///
return ZipEntry
		/// <summary>
		/// Do the work.
		/// </summary>
		protected override void OnExecute(ServerCommandProcessor theProcessor)
		{
			using (ZipFile zip = new ZipFile(_zipFile))
			{
				zip.ForceNoCompression = !NasSettings.Default.CompressZipFiles;
				zip.TempFileFolder = _tempFolder;
				zip.Comment = String.Format("Archive for study {0}", _studyXml.StudyInstanceUid);
				zip.UseZip64WhenSaving = Zip64Option.AsNecessary;

				// Add the studyXml file
				zip.AddFile(Path.Combine(_studyFolder,String.Format("{0}.xml",_studyXml.StudyInstanceUid)), String.Empty);

				// Add the studyXml.gz file
				zip.AddFile(Path.Combine(_studyFolder, String.Format("{0}.xml.gz", _studyXml.StudyInstanceUid)), String.Empty);

			    string uidMapXmlPath = Path.Combine(_studyFolder, "UidMap.xml");
                if (File.Exists(uidMapXmlPath))
                    zip.AddFile(uidMapXmlPath, String.Empty);

				// Add each sop from the StudyXmlFile
				foreach (SeriesXml seriesXml in _studyXml)
					foreach (InstanceXml instanceXml in seriesXml)
					{
						string filename = Path.Combine(_studyFolder, seriesXml.SeriesInstanceUid);
						filename = Path.Combine(filename, String.Format("{0}.dcm", instanceXml.SopInstanceUid));

						zip.AddFile(filename, seriesXml.SeriesInstanceUid);
					}

				zip.Save();
			}
		}
Example #2
0
        private string CreateArchiveFile()
        {
            string filename = Path.Combine(_storagePath, DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".zip");
            using(ZipFile output = new ZipFile())
            {
                output.UseZip64WhenSaving = Ionic.Zip.Zip64Option.AsNecessary;
                output.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                output.SortEntriesBeforeSaving = false;
                output.AddFile(Path.Combine(_storagePath, "content.index"), "");

                foreach (KeyValuePair<string, ContentRecord> rec in _content)
                {
                    string relpath = _content.GetContentFile(rec.Value);
                    if (relpath != null)
                    {
                        relpath = relpath.Substring(_storagePath.Length).TrimStart('\\', '/');
                        output.AddFile(Path.Combine(_storagePath, relpath), Path.GetDirectoryName(relpath));
                    }
                }

                string idxPath = Path.Combine(_storagePath, "index");
                if (Directory.Exists(idxPath))
                    foreach (string file in Directory.GetFiles(idxPath))
                        output.AddFile(file, "index");

                output.Save(filename);
            }
            return filename;
        }
        public static void SaveZipFile(this ISaveableContent saveable, string fileName)
        {
            // Make sure all files are relative
            List<string> allFiles = saveable.GetReferencedFiles(RelativeType.Absolute);

            string directory = FileManager.GetDirectory(fileName);

            foreach (string referencedFile in allFiles)
            {
                if (!FileManager.IsRelativeTo(referencedFile, directory))
                {
                    throw new InvalidOperationException("The file " +
                        referencedFile + " is not relative to the destination file " +
                        fileName + ".  All files must be relative to create a ZIP.");
                }
            }

            // First save the XML - we'll need this
            string xmlFileName = FileManager.RemoveExtension(fileName) + ".xmlInternal";
            FileManager.XmlSerialize(saveable, xmlFileName);

            using (ZipFile zip = new ZipFile())
            {
                // add this map file into the "images" directory in the zip archive
                zip.AddFile(xmlFileName);
                foreach (string referencedFile in allFiles)
                {
                    zip.AddFile(referencedFile);
                }
                zip.Save(fileName);
            }
        }
 private void button3_Click(object sender, RoutedEventArgs e)
 {
     Directory.SetCurrentDirectory("C:/tmp/soundpcker");
     using (ZipFile zip = new ZipFile())
     {
         // add this map file into the "images" directory in the zip archive
         zip.AddFile("pack.mcmeta");
         // add the report into a different directory in the archive
         zip.AddItem("assets");
         zip.AddFile("lcrm");
         zip.Save("CustomSoundInjector_ResourcePack.zip");
     }
         SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.DefaultExt = ".zip";
     saveFileDialog.Filter = "Minecraft ResourcePack (with Bytecode)|*.zip";
     if (saveFileDialog.ShowDialog() == true)
     {
         exportpath = saveFileDialog.FileName;
     }
     else
     {
         MessageBox.Show("Operation Cancelled.", "Cancelled", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     string originExport = "C:/tmp/soundpcker/CustomSoundInjector_ResourcePack.zip";
     File.Copy(originExport, exportpath, true);
     MessageBox.Show("Saved.", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
 }
Example #5
0
        public bool BackUp(string tableName)
        {
            string pathTable = databasePath + '/' + tableName + ".dat";
            string pathHash = databasePath + '/' + tableName + "_hash.dat";
            string pathFreeSpace = databasePath + '/' + tableName + "_freespace.dat";
            string pathHeaders = databasePath + '/' + tableName + "_headers.dat";
            try
            {
                using (ZipFile zip = new ZipFile())
                {
                    zip.AddFile(pathTable);
                    zip.AddFile(pathHash);
                    zip.AddFile(pathFreeSpace);
                    zip.AddFile(pathHeaders);

                    zip.Save(tableName + ".zip");
                }
                return true;
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
                return false;
            }
        }
        static void Main(string[] args)
        {
            const string releaseDir = @"";
            var assemblyPath = Path.Combine(Path.Combine(Environment.CurrentDirectory, releaseDir), "LINQPadLog4jDriver.dll");
            var assembly = Assembly.LoadFile(assemblyPath);
            var version = assembly.GetName().Version;

            using (var ms = new MemoryStream())
            using (var releaseZip = new ZipFile())
            using (var lpx45 = new ZipFile())
            {
                var releaseZipPath = Path.Combine(releaseDir, string.Format("Log4jLinqpadDriver {0}.zip", version));
                lpx45.AddFile(Path.Combine(Environment.CurrentDirectory, "LINQPadLog4jDriver.dll"), "");
                lpx45.AddFile(Path.Combine(Environment.CurrentDirectory, "header.xml"), "");
                lpx45.Save(ms);
                ms.Seek(0, SeekOrigin.Begin);
                releaseZip.AddEntry("Log4jLinqpadDriver.lpx", ms);

                releaseZip.Save(releaseZipPath);
                ms.SetLength(0);

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

            // open
            Process.Start(Environment.CurrentDirectory);
        }
        public ActionResult BatchDownload(string items)
        {
            var i = items.Split('_');
            var applications = db.Applications.Where(p => i.Contains(SqlFunctions.StringConvert((double)p.id).Trim()));

            var savePath = Server.MapPath("~/App_Data/");
            using (ZipFile zip = new ZipFile())
            {
                foreach (var application in applications)
                {
                    foreach (var attachment in application.ApplicationAttachments)
                    {
                        if (!String.IsNullOrEmpty(attachment.filename) && !String.IsNullOrEmpty(attachment.filepath))
                        {
                            var filename = attachment.filename;
                            var path = Server.MapPath("~/App_Data/" + attachment.filepath);
                            var filepath = Path.Combine(path, filename);
                            if (System.IO.File.Exists(filepath))
                            {
                                zip.AddFile(filepath, Path.Combine("ByApplication", application.StudentProfile.name + "[" + application.StudentProfile.academic_organization + "]" + "_" + application.StudentProfile.id + "_" + application.id));
                                //zip.AddFile(filepath, Path.Combine("ByAttachmentType", application.program_id.ToString() + "_" + HttpUtility.UrlEncode(application.Program.name), attachment.ProgramApplicationAttachment.name)).FileName = application.StudentProfile.name + "[" + application.StudentProfile.academic_organization + "]" + "_" + application.StudentProfile.id + "_" + application.id + "_" + filename;
                                zip.AddFile(filepath).FileName = Path.Combine("ByAttachmentType"
                                    , application.program_id.ToString() + "_" + HttpUtility.UrlEncode(application.Program.name)
                                    , attachment.ProgramApplicationAttachment.name
                                    , application.StudentProfile.name + "[" + application.StudentProfile.academic_organization + "]" + "_" + application.StudentProfile.id + "_" + application.id + "_" + filename);
                            }
                        }
                    }
                }
                zip.Save(savePath + "Archive.zip");
            }
            return File(savePath + "Archive.zip", "application/octet-stream", Path.GetFileName(savePath + "Archive.zip"));
        }
Example #8
0
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        PagedImages p = new PagedImages();
        zip.AddEntry(RESULT, p.CreatePdf());
        zip.AddFile(RESOURCE1, "");
        zip.AddFile(RESOURCE2, "");
        zip.AddFile(RESOURCE3, "");
        zip.Save(stream);
      }
    }    
Example #9
0
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        TransparentImage t = new TransparentImage();
        zip.AddEntry(RESULT, t.CreatePdf());
        zip.AddFile(RESOURCE1, "");
        zip.AddFile(RESOURCE2, "");
        zip.AddFile(RESOURCE3, "");
        zip.AddFile(RESOURCE4, "");
        zip.Save(stream);             
      }
    }
Example #10
0
 protected void btnZip_Click(object sender, EventArgs e)
 {
     using (ZipFile zip = new ZipFile())
     {
         // add this map file into the "images" directory in the zip archive
         zip.AddFile(@"E:\own\VS2012 Project\VipSoft\trunk\Demo\Web\ConfigHelper.cs","");
         // add the report into a different directory in the archive
         zip.AddFile(@"E:\own\VS2012 Project\VipSoft\trunk\Demo\Web\CriteriaTest.aspx", "");
         zip.Save(@"E:\own\VS2012 Project\VipSoft\trunk\Demo\Web\Jimmy.zip");
     }
 }
Example #11
0
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        zip.AddFile(JS1, "");
        zip.AddFile(JS2, "");
        zip.AddEntry("javascript.html", string.Format(HTML, RESULT));
        Subscribe s = new Subscribe();
        byte[] pdf = s.CreatePdf();
        JSForm j = new JSForm();
        zip.AddEntry(RESULT, j.ManipulatePdf(pdf));
        zip.Save(stream);
      }
    }
Example #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        using (var zip = new ZipFile())
        {
            var imagePath = Server.MapPath("~/Images/Sam.jpg");
            zip.AddFile(imagePath, string.Empty);
            zip.AddFile(imagePath, "My Images");

            zip.AddEntry("ZIPInfo.txt", "This ZIP file was created on " + DateTime.Now);

            var saveToFilePath = Server.MapPath("~/PictureOfSam2.zip");
            zip.Save(saveToFilePath);
        }
    }
Example #13
0
        public virtual string CreateBackupZip()
        {
            var dbFile = _enviromentProvider.GetNzbDronoeDbFile();
            var configFile = _enviromentProvider.GetConfigPath();
            var zipFile = _enviromentProvider.GetConfigBackupFile();

            using (var zip = new ZipFile())
            {
                zip.AddFile(dbFile, String.Empty);
                zip.AddFile(configFile, String.Empty);
                zip.Save(zipFile);
            }

            return zipFile;
        }
        public string ExpotZip(IQueryable <Models.OrderRecord> orders)
        {
            if (orders == null || orders.Count() == 0)
            {
                return("");
            }

            List <string> files = new List <string>();

            foreach (var item in orders)
            {
                files.Add(ExportOrderToInvoiceExcelFile(item.Id));
            }

            var zipFilename = DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".zip";

            zipFilename = System.Web.HttpContext.Current.Server.MapPath("/Media/Excel/tmp/" + zipFilename);



            using (Ionic.Zip.ZipFile Z = new Ionic.Zip.ZipFile())
            {
                foreach (string fileName in files)
                {
                    Z.AddFile(fileName);
                }
                Z.Save(zipFilename);
            }
            return(zipFilename);
        }
        public static void SendCrashReport(string body, string type)
        {
            try
            {
                string destfile = Path.Combine(Path.GetTempPath(), "error_report.zip");
                if (File.Exists(destfile))
                    File.Delete(destfile);

                using (var zip = new ZipFile(destfile))
                {
                        zip.AddFile(ServiceProvider.LogFile, "");
                        zip.Save(destfile);
                }
                var client = new MailgunClient("digicamcontrol.mailgun.org", "key-6n75wci5cpuz74vsxfcwfkf-t8v74g82");
                var message = new MailMessage("*****@*****.**", "*****@*****.**")
                                  {
                                      Subject = (type ?? "Log file"),
                                      Body = "Client Id" + (ServiceProvider.Settings.ClientId ?? "") + "\n" + body,
                                  };
                message.Attachments.Add(new Attachment(destfile));

                client.SendMail(message);
                message.Dispose();
            }
            catch (Exception )
            {

            }
        }
Example #16
0
 public void Comprimir()
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) {
         zip.AddFile("transacoes.csv");
         zip.Save("banco_de_dados.zip");
     }
 }
Example #17
0
 private void createSelfExtractingZip(MyFile mf)
 {
     try {
         NetworkDrives.MapDrive("iboxx");                                                                          //comment for local testing 3/26
         using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) {
             if (mf.IsFolder)
             {
                 zip.AddDirectory(mf.From);
             }
             else
             {
                 zip.AddFile(mf.From);
             }
             Ionic.Zip.SelfExtractorSaveOptions options = new Ionic.Zip.SelfExtractorSaveOptions();
             options.Flavor = Ionic.Zip.SelfExtractorFlavor.ConsoleApplication;
             zip.SaveSelfExtractor(mf.FullName, options);
         }
         NetworkDrives.DisconnectDrive("iboxx");                                                                   //comment for local testing
     } catch (Exception e) {
         displayError(e);
         throw;
         //if (Error == "") {
         //    Error = "Error caught in createSelfExtractingZip() " + e;
         //    throw;
         //}
         ////ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "Message", "<script>alert('Error caught in createSelfExtractingZip() " + e + "');</script>", true);
         ////this.Response.Write("<script>alert('Error caught in createSelfExtractingZip() " + e + "');</script>");
     }
 }
Example #18
0
        public static void ZipFiles(string zipFile, string rootPath, string[] files)
        {
			using (ZipFile zip = new ZipFile())
			{
				//use unicode if necessary
				zip.UseUnicodeAsNecessary = true;
				//skip locked files
				zip.ZipErrorAction = ZipErrorAction.Skip;
				foreach (string file in files)
				{
					string fullPath = Path.Combine(rootPath, file);
					if (Directory.Exists(fullPath))
					{
						//add directory with the same directory name
						zip.AddDirectory(fullPath, file);
					}
					else if (File.Exists(fullPath))
					{
						//add file to the root folder
						zip.AddFile(fullPath, "");
					}
				}
				zip.Save(zipFile);
			}
        }
Example #19
0
// ---------------------------------------------------------------------------         
    public void Write(Stream stream) {
      // Creating a reader
      string resource = Path.Combine(Utility.ResourcePdf, RESOURCE);
      PdfReader reader = new PdfReader(resource);
      Rectangle pagesize = reader.GetPageSizeWithRotation(1); 
      using (ZipFile zip = new ZipFile()) {
        // step 1
        using (MemoryStream ms = new MemoryStream()) {
          using (Document document = new Document(pagesize)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            PdfContentByte content = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            // adding the same page 16 times with a different offset
            float x, y;
            for (int i = 0; i < 16; i++) {
              x = -pagesize.Width * (i % 4);
              y = pagesize.Height * (i / 4 - 3);
              content.AddTemplate(page, 4, 0, 0, 4, x, y);
              document.NewPage();
            }
          }
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.AddFile(resource, "");
        zip.Save(stream);
      }
    }
Example #20
0
 /// <summary>
 /// 压缩ZIP文件
 /// </summary>
 /// <param name="fileList">待压缩的文件或目录集合</param>
 /// <param name="zipName">压缩后的文件名</param>
 /// <param name="isDirStruct">是否按目录结构压缩</param>
 public static bool Compress(List<string> fileList, string zipName, bool isDirStruct)
 {
     try
     {
         using (var zip = new ZipFile(Encoding.Default))
         {
             foreach (string path in fileList)
             {
                 string fileName = Path.GetFileName(path);
                 if (Directory.Exists(path))
                 {
                     //按目录结构压缩
                     if (isDirStruct)
                     {
                         zip.AddDirectory(path, fileName);
                     }
                     else//目录下文件压缩到根目录
                     {
                         zip.AddDirectory(path);
                     }
                 }
                 if (File.Exists(path))
                 {
                     zip.AddFile(path);
                 }
             }
             zip.Save(zipName);
             return true;
         }
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #21
0
        public HttpResponseMessage GetLog()
        {
            lock (_lockObj)
            {
                HttpResponseMessage response = Request.CreateResponse();
                using (var zip = new ZipFile())
                {
                    foreach (var path in _paths)
                    {
                        if (Directory.Exists(path))
                        {
                            zip.AddDirectory(path, Path.GetFileName(path));
                        }
                        else if (File.Exists(path))
                        {
                            zip.AddFile(path, String.Empty);
                        }
                    }

                    var ms = new MemoryStream();
                    zip.Save(ms);
                    response.Content = ms.AsContent();
                }
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                response.Content.Headers.ContentDisposition.FileName = String.Format("dump-{0:MM-dd-H:mm:ss}.zip", DateTime.UtcNow);
                return response;
            }
        }
Example #22
0
        /// <summary>
        /// Serialize
        /// </summary>
        /// <param name="site">site</param>
        /// <param name="path">path</param>
        /// <returns></returns>
        public void Serialize(Site site, string path)
        {
            if (site == null)
            {
                throw new ArgumentException("site");
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("stream");
            }

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

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

            }
            using (ZipFile package = new ZipFile(packagePath, Console.Out))
            {
                package.AddFile(tempPath, string.Empty);
                package.AddFiles(site.Resources.Select(r => r.TextData).Where(File.Exists), "resources");
                package.Save();
            }
        }
Example #23
0
        public override void Execute(object parameter)
        {
            var active = MainViewModel.ActiveDirectoryContainer.ActiveView;
            var dialog = new CompressDialog();
            if (dialog.ShowModalDialog())
            {
                using (var zipFile = new ZipFile())
                {
                    foreach (var item in MainViewModel.GetSelectedItems())
                    {
                        if (item.IsMoveUp)
                            continue;
                        else if (item.IsDirectory)
                            zipFile.AddDirectory(item.FullName);
                        else
                            zipFile.AddFile(item.FullName);
                    }

                    if (!string.IsNullOrEmpty(dialog.Password))
                    {
                        zipFile.Password = dialog.Password;
                        zipFile.Encryption = EncryptionAlgorithm.WinZipAes256;
                    }

                    zipFile.Save(Path.Combine(active.FullPath, dialog.FileName));
                }
            }
        }
Example #24
0
 public static void BuildPackage(IEnumerable<string> includes, string outputFileName)
 {
     File.Delete(outputFileName);
     using (var zipFile = new ZipFile(outputFileName))
     {
         foreach (var include in includes)
         {
             if (include.Length < 3)
             {
                 throw new PackManException("Include option must have following format: f|d|p:<value>.");
             }
             char type = char.ToLower(include[0]);
             string value = include.Substring(2);
             switch (type)
             {
                 case 'f':
                     zipFile.AddFile(value);
                     break;
                 case 'd':
                     zipFile.AddDirectory(value);
                     break;
                 case 'p':
                     zipFile.AddSelectedFiles(value,true);
                     break;
             }
         }
         zipFile.Save();
     }
 }
Example #25
0
        public static void DoubleZipFileContent(string folderSource, string fileDest, string password)
        {
            using (var zip = new ZipFile())
            {
                zip.AlternateEncoding = Encoding.UTF8;
                zip.AlternateEncodingUsage = ZipOption.Always;

                zip.Password = password;
                zip.Encryption = EncryptionAlgorithm.WinZipAes128;
                zip.AddDirectory(folderSource);
                zip.Save(Path.Combine(folderSource, "content.zip"));
            }

            using (var doubleZip = new ZipFile())
            {
                doubleZip.AlternateEncoding = Encoding.UTF8;
                doubleZip.AlternateEncodingUsage = ZipOption.Always;

                doubleZip.Password = password;
                doubleZip.Encryption = EncryptionAlgorithm.WinZipAes128;
                doubleZip.AddFile(Path.Combine(folderSource, "content.zip"), "");
                doubleZip.Save(fileDest);
            }

            if (File.Exists(Path.Combine(folderSource, "content.zip")))
                File.Delete(Path.Combine(folderSource, "content.zip"));
        }
Example #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt = cm.getdt("SELECT * FROM VW_RFI_ATCH_DTL_ALL_ZIP WHERE RAD_RFH_ID = 97");
        string output = "<style> table { min-width:600px; padding: 0px; box-shadow: 2px 2px 3px #888888; border: 1px solid #cccccc; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } table table { height: 100%; margin: 0px; padding: 0px; } table tr:last-child td:last-child { -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; } table table tr:first-child td:first-child { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; } table table tr:first-child td:last-child { -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; } table tr:last-child td:first-child { -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; } table tr:hover td { background-color: #e5e5e5; } table td { vertical-align: middle; background: -o-linear-gradient(bottom, #ffffff 5%, #e5e5e5 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #e5e5e5) ); background: -moz-linear-gradient( center top, #ffffff 5%, #e5e5e5 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e5e5e5'); background: -o-linear-gradient(top,#ffffff,e5e5e5); background-color: #ffffff; border: 1px solid #cccccc; border-width: 0px 1px 1px 0px; text-align: left; padding: 7px 4px 7px 4px; font-size: 10px; font-family: Arial; font-weight: normal; color: #000000; } table tr:last-child td { border-width: 0px 1px 0px 0px; } table tr td:last-child { border-width: 0px 0px 1px 0px; } table tr:last-child td:last-child { border-width: 0px 0px 0px 0px; } table tr:first-child td { background: -o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background: -moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#b2b2b2'); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color: #cccccc; border: 0px solid #cccccc; text-align: center; border-width: 0px 0px 1px 1px; font-size: 12px; font-family: Arial; font-weight: bold; color: #000000; } table tr:first-child:hover td { background: -o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) ); background: -moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#b2b2b2'); background: -o-linear-gradient(top,#cccccc,b2b2b2); background-color: #cccccc; } table tr:first-child td:first-child { border-width: 0px 0px 1px 0px; } table tr:first-child td:last-child { border-width: 0px 0px 1px 1px; } table th { background: -o-linear-gradient(bottom, #ffffff 5%, #e5e5e5 100%); background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ffffff), color-stop(1, #e5e5e5) ); background: -moz-linear-gradient( center top, #ffffff 5%, #e5e5e5 100% ); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e5e5e5'); background: -o-linear-gradient(top,#ffffff,e5e5e5); background-color: #ffffff; border: 1px solid #888888; padding: 3px; font-family: Arial; font-size: 12px; } body { font-family: Arial; font-size: 12px; } </style>";
        output += "<div style=''><b>RFI for " + dt.Rows[0]["RAD_RFH_RFINO"].ToString() + "</b></div>";

        using (ZipFile zip = new ZipFile())
        {
            zip.AlternateEncodingUsage = ZipOption.Never;
            output += "<table>";
            output += "<tr><th>RFI Attach Type</th><th>Insepection</th><th>Remark</th><th>Date</th></tr>";
            foreach (DataRow row in dt.Rows)
            {
                output += "<tr>";
                if (File.Exists(Server.MapPath(row["RAD_FILE_SRVR"].ToString())))
                {
                    zip.AddFile(Server.MapPath(row["RAD_FILE_SRVR"].ToString()), (row["file_path"].ToString()));
                    output += "<td>";
                    output += (row["RAD_FILE_SRVR_link"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_VAL_TYPE"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_REMARKS"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_DOC_DT"].ToString());
                    output += "</td>";
                }
                else
                {
                    output += "<td>";
                    output += "No file found";
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_VAL_TYPE"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_REMARKS"].ToString());
                    output += "</td>";
                    output += "<td>";
                    output += (row["RAD_DOC_DT"].ToString());
                    output += "</td>";
                    //zip.AddFile("");
                }
                output += "</tr>";
            }
            output += "</table>";
            byte[] data = Encoding.UTF8.GetBytes(output);
            zip.AddEntry("info.html", data);
            Response.Clear();
            Response.BufferOutput = false;
            Response.ContentType = "application/zip";
            Response.AddHeader("content-disposition", "attachment; filename=Zip_" + DateTime.Now.ToString("yyyy-MMM-dd-HHmmss") + ".zip");
            zip.Save(Response.OutputStream);
            Response.End();
        }
    }
Example #27
0
        public bool CreatePackage(string filename, bool includeWalkthrough, out string error)
        {
            error = string.Empty;

            try
            {
                string data = m_worldModel.Save(SaveMode.Package, includeWalkthrough);
                string baseFolder = System.IO.Path.GetDirectoryName(m_worldModel.Filename);

                using (ZipFile zip = new ZipFile(filename))
                {
                    zip.AddEntry("game.aslx", data, Encoding.UTF8);
                    foreach (string file in m_worldModel.GetAvailableExternalFiles("*.jpg;*.jpeg;*.png;*.gif;*.js;*.wav;*.mp3;*.htm;*.html"))
                    {
                        zip.AddFile(System.IO.Path.Combine(baseFolder, file), "");
                    }
                    AddLibraryResources(zip, baseFolder, ElementType.Javascript);
                    AddLibraryResources(zip, baseFolder, ElementType.Resource);
                    zip.Save();
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }

            return true;
        }
Example #28
0
        protected override Task<HttpResponseMessage> CreateDirectoryGetResponse(DirectoryInfo info, string localFilePath)
        {
            HttpResponseMessage response = Request.CreateResponse();
            using (var zip = new ZipFile())
            {
                foreach (FileSystemInfo fileSysInfo in info.EnumerateFileSystemInfos())
                {
                    bool isDirectory = (fileSysInfo.Attributes & FileAttributes.Directory) != 0;

                    if (isDirectory)
                    {
                        zip.AddDirectory(fileSysInfo.FullName, fileSysInfo.Name);
                    }
                    else
                    {
                        // Add it at the root of the zip
                        zip.AddFile(fileSysInfo.FullName, "/");
                    }
                }

                using (var ms = new MemoryStream())
                {
                    zip.Save(ms);
                    response.Content = ms.AsContent();
                }
            }

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            // Name the zip after the folder. e.g. "c:\foo\bar\" --> "bar"
            response.Content.Headers.ContentDisposition.FileName = Path.GetFileName(Path.GetDirectoryName(localFilePath)) + ".zip";
            return Task.FromResult(response);
        }
Example #29
0
// --------------------------------------------------------------------------- 
    public void Write(Stream stream) {    
      using (ZipFile zip = new ZipFile()) {
        byte[] circledata = { 
          (byte) 0x3c, (byte) 0x7e, (byte) 0xff, (byte) 0xff, 
          (byte) 0xff, (byte) 0xff, (byte) 0x7e, (byte) 0x3c 
        };
        Image mask = Image.GetInstance(8, 8, 1, 1, circledata);
        mask.MakeMask();
        mask.Inverted = true;
        
        ImageMask im = new ImageMask();
        zip.AddEntry(RESULT1, im.CreatePdf(mask));
        
        byte[] gradient = new byte[256];
        for (int i = 0; i < 256; i++) {
          gradient[i] = (byte) i;
        }
        mask = Image.GetInstance(256, 1, 1, 8, gradient);
        mask.MakeMask();
        im = new ImageMask();
        zip.AddEntry(RESULT2, im.CreatePdf(mask));

        zip.AddFile(RESOURCE, "");
        zip.Save(stream);             
      }
    }
Example #30
0
// ---------------------------------------------------------------------------    
    public virtual void Write(Stream stream) {  
      using (ZipFile zip = new ZipFile()) { 
        // Get the movies
        IEnumerable<Movie> movies = PojoFactory.GetMovies();
        string datasheet = Path.Combine(Utility.ResourcePdf, DATASHEET); 
        string className = this.ToString();            
        // Fill out the data sheet form with data
        foreach (Movie movie in movies) {
          if (movie.Year < 2007) continue;
          PdfReader reader = new PdfReader(datasheet);          
          string dest = string.Format(RESULT, movie.Imdb);
          using (MemoryStream ms = new MemoryStream()) {
            using (PdfStamper stamper = new PdfStamper(reader, ms)) {
              AcroFields fields = stamper.AcroFields;
              fields.GenerateAppearances = true;
              Fill(fields, movie);
              if (movie.Year == 2007) stamper.FormFlattening = true;
            }
            zip.AddEntry(dest, ms.ToArray());
          }         
        }
        zip.AddFile(datasheet, "");
        zip.Save(stream);
      }              
    }
    public static void Zip(string zipFileName, params string[] files)
    {
        #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
        string path = Path.GetDirectoryName(zipFileName);
        Directory.CreateDirectory(path);

        using (ZipFile zip = new ZipFile())
        {
            foreach (string file in files)
            {
                zip.AddFile(file, "");
            }
            zip.Save(zipFileName);
        }
        #elif UNITY_ANDROID
        using (AndroidJavaClass zipper = new AndroidJavaClass ("com.tsw.zipper")) {
            {
                zipper.CallStatic ("zip", zipFileName, files);
            }
        }
        #elif UNITY_IPHONE
        foreach (string file in files) {
            addZipFile (file);
        }
        zip (zipFileName);
        #endif
    }
Example #32
0
        static void Main(string[] args)
        {
            try
            {
                ZipDestinationPath = Path.Combine(Application.StartupPath, "..\\..\\..\\MovieFinder.Web\\App_Data\\MovieTube.zip");
                var configPath = Path.Combine(Application.StartupPath, "..\\..\\..\\MovieFinder.Web\\Web.config");
                Version version;
                if (!IsVersionChanged(out version))
                    return;

                if (File.Exists(ZipFileName))
                    File.Delete(ZipFileName);

                using (var zip = new ZipFile())
                {
                    foreach (var f in Files)
                        zip.AddFile(f, "");

                    zip.Save(ZipFileName);
                    File.Copy(ZipFileName, ZipDestinationPath, true);
                }

                var doc = XDocument.Load(configPath);
                var elem = doc.Root.Descendants("add").Where(x => (string)x.Attribute("key") == "AppVersion").Single().Attribute("value");
                elem.Value = version.ToString();
                doc.Save(configPath);
                MessageBox.Show("New version updated");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string txtVendorId = Request.QueryString["vendor"];
        string txtBidRefNo = Request.QueryString["bid"];

        Response.Clear();
        Response.BufferOutput = false;
        Response.ContentType  = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=TenderAttachments_Bid_" + txtBidRefNo.ToString() + "_Vendor_" + txtVendorId.ToString() + ".zip"); // File name of a zip file

        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
        {
            string vendorName = String.Empty;
            string path2tmp   = String.Empty;

            sCommand = "SELECT * FROM tblVendorFileUploads WHERE BidRefNo=" + txtBidRefNo.ToString() + " AND VendorID=" + txtVendorId.ToString() + " AND AsDraft=0";
            string        connstring = HttpContext.Current.Session["ConnectionString"].ToString();
            SqlDataReader oReader    = SqlHelper.ExecuteReader(connstring, CommandType.Text, sCommand);
            if (oReader.HasRows)
            {
                string fileNameActual = String.Empty;
                string fileNameOrig   = String.Empty;
                oReader.Read();
                string path = Constant.FILEATTACHMENTSFOLDERDIR;
                fileNameActual = path + '\\' + txtVendorId.ToString() + '\\' + txtBidRefNo.ToString() + '\\' + oReader["ActualFileName"].ToString();
                fileNameOrig   = oReader["OriginalFileName"].ToString();
                if (File.Exists(fileNameActual))
                {
                    zip.AddFile(fileNameActual).FileName = fileNameOrig;
                }
            }
            oReader.Close();
            //Response.Write(sCommand);

            //foreach (GridViewRow row1 in gvInvitedSuppliers.Rows)
            //{
            //    if (row1.FindControl("lnkDownload") != null && row1.FindControl("txtFileAttachment") != null)
            //    {
            //        vendorName = (row1.FindControl("txtVendorNme") as HiddenField).Value.ToString().Replace("'", "").Replace(",", " ").Replace(".", " ");
            //        fileNameActual = (row1.FindControl("lnkDownload") as LinkButton).Text;
            //        path2tmp = (row1.FindControl("txtFileAttachment") as HiddenField).Value.ToString();
            //        string[] args = path2tmp.Split(new char[] { '|' });
            //        string path = Constant.FILEATTACHMENTSFOLDERDIR;
            //        string[] folder = args[0].Split(new char[] { '_' });
            //        path = path + folder[1].ToString() + '\\' + folder[2].ToString() + '\\';
            //        fileNameActual = path + args[0];
            //        //fileNameOrig = folder[1].ToString() + '\\' + args[1];
            //        fileNameOrig = vendorName + '\\' + args[1];
            //        if (File.Exists(fileNameActual))
            //        {
            //            zip.AddFile(fileNameActual).FileName = fileNameOrig;
            //        }
            //    }
            //}
            zip.Save(Response.OutputStream);
        }

        Response.Close();
    }
 public void CompressFile(string filePath)
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
     {
         zip.AddFile(filePath);
         zip.Save(filePath + ".zip");
     }
     File.WriteAllText(filePath, string.Empty);
 }
Example #35
0
        private static void addFileToZipObjectIfPathExists(Ionic.Zip.ZipFile zipfile, string itpipesDirectory, string pathToFile)
        {
            if (File.Exists(pathToFile))
            {
                string relativePath = Path.GetDirectoryName(pathToFile.Replace(itpipesDirectory, ""));

                zipfile.AddFile(pathToFile, relativePath);
            }
        }
Example #36
0
 protected void Zip(string fileName, string zipFileName, string password)
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
     {
         zip.Password = password;
         zip.AddFile(fileName);
         zip.Save(zipFileName);
     }
 }
Example #37
0
            public void CompressFile(string fileName, string archiveFileName)
            {
#if (NET3_5 || NET4_0 || NET4_5) && !NETSTANDARD
                using (var zip = new Ionic.Zip.ZipFile())
                {
                    zip.AddFile(fileName);
                    zip.Save(archiveFileName);
                }
#endif
            }
Example #38
0
        public static void zipbase(string pathFile)
        {
            ZipFileToCreate = Application.StartupPath + @"\Backup\Magbase.zip";

            using (Basezip.ZipFile zip = new Basezip.ZipFile())
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                Basezip.ZipEntry ze = zip.AddFile(pathFile);
                zip.Save(ZipFileToCreate);
            }
        }
Example #39
0
            public void CompressFile(string fileName, string archiveFileName, string entryName)
            {
#if !NETSTANDARD
                using (var zip = new Ionic.Zip.ZipFile())
                {
                    ZipEntry entry = zip.AddFile(fileName);
                    entry.FileName = entryName;
                    zip.Save(archiveFileName);
                }
#endif
            }
    private void ZipFiles()
    {
        string path = Server.MapPath("/dump/");

        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
        {
            foreach (string file in System.IO.Directory.GetFiles(path, "*.csv"))
            {
                zip.AddFile(file, "/");
            }
            zip.Save(path + "export.zip");
        }
    }
Example #41
0
        /// <summary>
        /// สำหรับ Zip ไฟล์และ Download
        /// </summary>
        /// <param name="httpResponse">Response ของ Page</param>
        /// <param name="reqDate">วันที่ต้องการ Download</param>
        /// <param name="tempFolder">Temp Folder</param>
        public void DownloadLicenseZip(System.Web.HttpResponse httpResponse, DateTime reqDate, string tempFolder)
        {
            //เตรียม Directory และ ไฟล์ที่ต้องการ Download
            string dir = InitRequestLicenseFileToDownload(tempFolder, reqDate);

            //สำหรับเก็บ Folder ที่ต้อง Zip เพื่อวนหาไฟล์ใน Folder
            List <string> list = new List <string>();

            list.Add(dir);

            //วนหา Folder ที่ต้อง Zip และ SubFolder ที่อยู่ภายใน
            GetAllFiles(list, dir);

            string folderName = string.Empty;

            //สร้าง  Instantce Zip
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                //กำหนด Option Endcode
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;

                //วนเ Folder และ SubFolder
                for (int i = 0; i < list.Count; i++)
                {
                    //Folder ปัจจุบัน
                    DirectoryInfo dInfo = new DirectoryInfo(list[i]);
                    folderName += (i == 0 ? "" : "\\") + dInfo.Name;

                    //สร้าง Folder ใน Zip
                    zip.AddDirectoryByName(folderName);

                    //วน Add File ใน Folder
                    foreach (string f in Directory.GetFiles(list[i]))
                    {
                        zip.AddFile(f, folderName);
                    }
                }


                httpResponse.Clear();
                httpResponse.BufferOutput = false;
                string zipName = String.Format("{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                httpResponse.ContentType = "application/zip";
                httpResponse.AddHeader("content-disposition", "attachment; filename=" + zipName);
                zip.Save(httpResponse.OutputStream);
                httpResponse.End();
            }
        }
        public string comprimir_Carpetas_ant(string nombreFile)
        {
            string resultado = "";

            try
            {
                string ruta_origen  = ConfigurationManager.AppSettings["ruta_origen"];
                string ruta_destino = ConfigurationManager.AppSettings["ruta_destino"] + "julio.zip";

                List <string> items = new List <string>();
                items.Add(ruta_origen + "Juliodoc");   //---carpeta
                items.Add(ruta_origen + "chokis.jpg"); //---- archivos normales

                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (string item in items)
                    {
                        if (System.IO.File.Exists(item))
                        {
                            //agregando un archivo normal
                            zip.AddFile(item, "");
                        }   // if the item is a folder
                        else if (System.IO.Directory.Exists(item))
                        {
                            // añadiendo una carpeta con todo sus sub directorios
                            zip.AddDirectory(item, new System.IO.DirectoryInfo(item).Name);
                        }
                    }
                    // Guardando el archivo zip
                    zip.Save(ruta_destino);
                }
                if (File.Exists(ruta_destino))
                {
                    resultado = "El proceso finalizo.";
                }
                else
                {
                    resultado = "No se genero";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(resultado);
        }
        public string comprimir_Carpetas(List <download> list_download, int usuario_creacion)
        {
            string resultado = "";

            try
            {
                string ruta_destino  = System.Web.Hosting.HostingEnvironment.MapPath("~/Documentos/Descargas/" + usuario_creacion + "_Descarga.zip");
                string ruta_descarga = ConfigurationManager.AppSettings["servidor_files"] + "Descargas/" + usuario_creacion + "_Descarga.zip";

                if (File.Exists(ruta_destino)) //--- restaurarlo
                {
                    System.IO.File.Delete(ruta_destino);
                }
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    foreach (download item in list_download)
                    {
                        if (System.IO.File.Exists(item.ubicacion))
                        {
                            //agregando un archivo normal
                            zip.AddFile(item.ubicacion, "");
                        }   // if the item is a folder
                        else if (System.IO.Directory.Exists(item.ubicacion))
                        {
                            zip.AddDirectory(item.ubicacion, new System.IO.DirectoryInfo(item.ubicacion).Name);
                        }
                    }
                    // Guardando el archivo zip
                    zip.Save(ruta_destino);
                }
                if (File.Exists(ruta_destino))
                {
                    resultado = ruta_descarga;
                }
                else
                {
                    throw new System.InvalidOperationException("No se pudo generar la Descarga del Archivo");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(resultado);
        }
Example #44
0
 /// <summary>
 /// Compacta uma lista de arquivo em um arquivo .zip
 /// </summary>
 /// <param name="files"></param>Arquivos
 /// <param name="zipOut"></param>Arquivo .zip de saida
 /// <returns></returns>true compactado ou false erro
 public static void CompressFileList(List <string> files, string zipOut)
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
     {
         // percorre todos os arquivos da lista
         foreach (string item in files)
         {
             // se o item é um arquivo
             if (File.Exists(item))
             {
                 try
                 {
                     // Adiciona o arquivo na pasta raiz dentro do arquivo zip
                     zip.AddFile(item, "");
                 }
                 catch (Exception ex)
                 {
                     throw ex;
                 }
             }
             // se o item é uma pasta
             else if (Directory.Exists(item))
             {
                 try
                 {
                     // Adiciona a pasta no arquivo zip com o nome da pasta
                     zip.AddDirectory(item, new DirectoryInfo(item).Name);
                 }
                 catch
                 {
                     throw;
                 }
             }
         }
         // Salva o arquivo zip para o destino
         try
         {
             zip.Save(zipOut);
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
Example #45
0
    /// <summary>
    /// Creates a zip file containing the given input files
    /// </summary>
    /// <param name="ZipFileName">Filename for the zip</param>
    /// <param name="Filter">Filter which selects files to be included in the zip</param>
    /// <param name="BaseDirectory">Base directory to store relative paths in the zip file to</param>
    /// <param name="CopyModeOnly">No compression will be done. Only acts like a container. The default value is set to false.</param>
    internal static void InternalZipFiles(FileReference ZipFileName, DirectoryReference BaseDirectory, FileFilter Filter, int CompressionLevel = 0)
    {
        // Ionic.Zip.Zip64Option.Always option produces broken archives on Mono, so we use system zip tool instead
        if (Utils.IsRunningOnMono)
        {
            DirectoryReference.CreateDirectory(ZipFileName.Directory);
            CommandUtils.PushDir(BaseDirectory.FullName);
            string FilesList = "";
            foreach (FileReference FilteredFile in Filter.ApplyToDirectory(BaseDirectory, true))
            {
                FilesList += " \"" + FilteredFile.MakeRelativeTo(BaseDirectory) + "\"";
                if (FilesList.Length > 32000)
                {
                    CommandUtils.RunAndLog(CommandUtils.CmdEnv, "zip", "-g -q \"" + ZipFileName + "\"" + FilesList);
                    FilesList = "";
                }
            }
            if (FilesList.Length > 0)
            {
                CommandUtils.RunAndLog(CommandUtils.CmdEnv, "zip", "-g -q \"" + ZipFileName + "\"" + FilesList);
            }
            CommandUtils.PopDir();
        }
        else
        {
            using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile())
            {
                Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;

                Zip.CompressionLevel = (Ionic.Zlib.CompressionLevel)CompressionLevel;

                if (Zip.CompressionLevel == Ionic.Zlib.CompressionLevel.Level0)
                {
                    Zip.CompressionMethod = Ionic.Zip.CompressionMethod.None;
                }

                foreach (FileReference FilteredFile in Filter.ApplyToDirectory(BaseDirectory, true))
                {
                    Zip.AddFile(FilteredFile.FullName, Path.GetDirectoryName(FilteredFile.MakeRelativeTo(BaseDirectory)));
                }
                CommandUtils.CreateDirectory(Path.GetDirectoryName(ZipFileName.FullName));
                Zip.Save(ZipFileName.FullName);
            }
        }
    }
Example #46
0
    public void DownloadZipFiles(string fileName, Dictionary <string, string> files)
    {
        string zipname = Path.Combine(Path.GetTempPath(), fileName);

        using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile())
        {
            foreach (var file in files)
            {
                zipFile.AddFile(file.Value, "");
            }
            zipFile.Save(zipname);
        }
        Response.Clear();
        Response.ContentType = "application/zip";
        Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
        Response.WriteFile(zipname);
        Response.End();
    }
Example #47
0
        public override void Build()
        {
            UpdateNlib();
            string outp = BuildPath + "main.js";

            File.Delete(outp);
            foreach (var library in Libraries)
            {
                string text = library.GetCode();
                File.AppendAllText(outp, "\n" + text, ProgramData.Encoding);
            }
            foreach (var file in Directory.GetFiles(ScriptsPath))
            {
                string text = File.ReadAllText(file, ProgramData.Encoding);
                File.AppendAllText(outp, "\n" + text, ProgramData.Encoding);
            }
            if (Compress)
            {
                JavaScriptCompressor compressor = new JavaScriptCompressor();
                File.WriteAllText(outp, compressor.Compress(File.ReadAllText(outp, ProgramData.Encoding)), ProgramData.Encoding);
            }

            foreach (var file in OutFiles)
            {
                File.Copy(file, BuildPath + System.IO.Path.GetFileName(file), true);
                File.Copy(file, OutPath + System.IO.Path.GetFileName(file), true);
            }

            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectoryByName("images");
                zip.AddDirectory(ResPath, "images");
                zip.Save(BuildPath + "resources.zip");
            }

            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.AddDirectoryByName("script");
                zip.AddFile(outp, "script");
                zip.AddDirectoryByName("images");
                zip.AddDirectory(ResPath, "images");
                zip.Save(OutPath + Name + ".modpkg");
            }
        }
        public static bool WriteFileToZip(TriggerReader reader)
        {
            string fileToZip = reader.ReadString();
            string zipFile   = reader.ReadString();

            try
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile))
                {
                    zip.AddFile(fileToZip);
                    zip.Save();
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
 public bool ZipGenerator(string FILENAME, string PASSWORD, string ZIP_STORAGEFOLDER_PATH, string DECOMPRESS_FILE_NAME)
 {
     try
     {
         using (var zip = new ZipFile())
         {
             zip.AlternateEncoding      = System.Text.Encoding.UTF8;
             zip.AlternateEncodingUsage = ZipOption.Always;
             zip.Password   = PASSWORD;
             zip.Encryption = EncryptionAlgorithm.WinZipAes256;
             zip.AddFile(FILENAME, "").FileName = DECOMPRESS_FILE_NAME;
             zip.Save(ZIP_STORAGEFOLDER_PATH);
         }
         return(true);
     }
     catch (Exception) {
         return(false);
     }
 }
Example #50
0
        /// <summary>
        /// 压缩zip
        /// </summary>
        /// <param name="fileToZips">文件路径集合</param>
        /// <param name="zipedFile">想要压成zip的文件名</param>
        public static void Zip(string[] fileToZips, string zipedFile, string basePath)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.UTF8))
            {
                foreach (string fileToZip in fileToZips)
                {
                    if (System.IO.File.Exists(fileToZip))
                    {
                        zip.AddFile(fileToZip, fileToZip.Substring(basePath.Length, fileToZip.LastIndexOf('\\') - basePath.Length));
                        continue;
                    }

                    if (System.IO.Directory.Exists(fileToZip))
                    {
                        zip.AddDirectory(fileToZip, fileToZip.Substring(basePath.Length));
                    }
                }
                zip.Save();
            }
        }
Example #51
0
        public async Task <IActionResult> DownloadFiles(string device, DateTime initialDate, DateTime finalDate)
        {
            string date = DateTime.Now.ToString("yyyyMMdd") + ".gz";

            device = Request.Form["device"];
            string start = Request.Form["start"];
            string end   = Request.Form["end"];

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var enc1252 = Encoding.GetEncoding(1252);

            DirectoryInfo DI = new DirectoryInfo("files/" + device + "/gzip");

            Ionic.Zip.ZipFile zip;

            var ifp = _fileProvider.GetDirectoryContents("/files/" + device + "/gzip");

            using (zip = new Ionic.Zip.ZipFile())
            {
                foreach (var item in ifp)
                {
                    if (item.Name.ToString().Substring(item.Name.ToString().IndexOf('.'), 5) == ".flac" && item.Name.ToString().Length == 18)
                    {
                        zip.AddFile(item.PhysicalPath, "");
                    }
                }
                zip.Save(DI.FullName + @"/" + date);
            }



            // DOWNLOADING FILE
            string fileAddress = DI.FullName + @"/" + date;
            var    net         = new System.Net.WebClient();
            var    data        = net.DownloadData(fileAddress);
            var    content     = new System.IO.MemoryStream(data);

            System.IO.File.Delete("files/" + device + "/gzip/" + date);

            return(File(content, "APPLICATION/octet-stream", date));
        }
Example #52
0
    /// <summary>
    /// Creates a zip file containing the given input files
    /// </summary>
    /// <param name="ZipFileName">Filename for the zip</param>
    /// <param name="Filter">Filter which selects files to be included in the zip</param>
    /// <param name="BaseDirectory">Base directory to store relative paths in the zip file to</param>
    /// <param name="CopyModeOnly">No compression will be done. Only acts like a container. The default value is set to false.</param>
    internal static void InternalZipFiles(FileReference ZipFileName, DirectoryReference BaseDirectory, FileFilter Filter, int CompressionLevel = 0)
    {
        using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile())
        {
            Zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.AsNecessary;

            Zip.CompressionLevel = (Ionic.Zlib.CompressionLevel)CompressionLevel;

            if (Zip.CompressionLevel == Ionic.Zlib.CompressionLevel.Level0)
            {
                Zip.CompressionMethod = Ionic.Zip.CompressionMethod.None;
            }

            foreach (FileReference FilteredFile in Filter.ApplyToDirectory(BaseDirectory, true))
            {
                Zip.AddFile(FilteredFile.FullName, Path.GetDirectoryName(FilteredFile.MakeRelativeTo(BaseDirectory)));
            }
            CommandUtils.CreateDirectory(Path.GetDirectoryName(ZipFileName.FullName));
            Zip.Save(ZipFileName.FullName);
        }
    }
Example #53
0
        /// <summary>
        /// Compacta uma lista de arquivo em um arquivo .zip
        /// </summary>
        /// <param name="files"></param>Arquivos
        /// <param name="zipOut"></param>Arquivo .zip de saida
        /// <returns></returns>true compactado ou false erro
        public static bool CompressFiles(string[] files, string zipOut)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                try
                {
                    // percorre todos os arquivos da lista
                    foreach (string f in files)
                    {
                        // se o item é um arquivo
                        if (File.Exists(f))
                        {
                            // Adiciona o arquivo na pasta raiz dentro do arquivo zip
                            zip.AddFile(f, "");
                        }
                        // se o item é uma pasta
                        else if (Directory.Exists(f))
                        {
                            // Adiciona a pasta no arquivo zip com o nome da pasta
                            zip.AddDirectory(f, new DirectoryInfo(f).Name);
                        }
                    }

                    // Salva o arquivo zip para o destino
                    zip.Save(zipOut);

                    //tudo certo
                    return(true);
                }
                catch (Exception ex)
                {
                    LoggerUtilIts.ShowExceptionLogs(ex);
                    XMessageIts.ExceptionJustMessage(ex, "Falha ao compactar o arquivo");
                    //deu merda
                    return(false);
                }
            }
        }
Example #54
0
        public void Export(bool rewrite = false)
        {
            try
            {
                XmlWriter xmlio;
                if (File.Exists(Filename + ".sft") && rewrite == false)
                {
                    throw new Exceptions.FileExists();
                }
                if (!Directory.Exists("res"))
                {
                    Directory.CreateDirectory("res");
                }
                fs    = new FileStream("script.ist", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                xmlio = XmlWriter.Create(fs);
                sr    = new StreamReader(fs);

                xmlio.WriteStartElement("subject"); //root
                xmlio.WriteAttributeString("name", Name);

                xmlio.WriteStartElement("settings");  //setings part

                xmlio.WriteStartElement("showright"); //define show right after asking on task
                xmlio.WriteString((ShowRight == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("allowremake"); //define can student pass this subject again
                xmlio.WriteString((AllowRemake == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("randomtask"); //define should be task sorted by order or presented randomly
                xmlio.WriteString((Randomtask == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("randomanswer");//define should answers be presented randomly
                xmlio.WriteString((RandomAnswerOrder == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("usetimer");                        //define time to pass task
                xmlio.WriteAttributeString("time", Convert.ToString(Time)); //write time per task, if time wasn't defined, time = -1
                xmlio.WriteString((UseTime == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteStartElement("limittasks");//define task limitation in one test
                xmlio.WriteAttributeString("tasks", Convert.ToString(LimitedTasksAmount));
                xmlio.WriteString((LimitTasks == true) ? "True" : "False");
                xmlio.WriteEndElement();

                xmlio.WriteEndElement();          //close setings part

                xmlio.WriteStartElement("tasks"); //open tasks part

                foreach (TaskClass task in Tasks)
                {
                    xmlio.WriteStartElement("task");   //define task

                    xmlio.WriteStartElement("header"); //write header of task
                    xmlio.WriteString(task.Label);
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("text"); //write text of the task
                    xmlio.WriteString(task.Text);
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("images"); //write images pathes

                    int counter = 0;
                    foreach (KeyValuePair <Image, string> img in task.Images)
                    {
                        string path  = @"res/img" + task.Label + counter + ".jpg";
                        Image  image = img.Key;
                        image.Save(path);
                        xmlio.WriteElementString("image", path);
                        counter++;
                    }
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("answertype");
                    xmlio.WriteString(Convert.ToString(task.Answer_Type));
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("answers");
                    foreach (string answer in task.Answers)
                    {
                        xmlio.WriteStartElement("answer");
                        xmlio.WriteString(answer);
                        xmlio.WriteEndElement();
                    }
                    xmlio.WriteEndElement();

                    xmlio.WriteStartElement("right");
                    xmlio.WriteString(task.Answer);
                    xmlio.WriteEndElement();

                    xmlio.WriteEndElement();//close task
                }
                xmlio.WriteEndElement();
                xmlio.WriteStartElement("marks");
                foreach (MarkClass mrk in Marks)
                {
                    xmlio.WriteStartElement("mark");
                    xmlio.WriteElementString("percentage", Convert.ToString(mrk.Percentage));
                    xmlio.WriteElementString("name", mrk.Mark);
                    xmlio.WriteEndElement();
                }
                xmlio.WriteEndElement();
                xmlio.Flush();
                long   position = fs.Position;
                string has      = CalculateHash();
                fs.Position = position;
                xmlio.WriteStartElement("hashMD5");
                xmlio.WriteString(has);
                xmlio.WriteEndElement();


                xmlio.WriteEndElement();

                xmlio.WriteEndDocument();
                xmlio.Close();

                fs.Close();

                Ionic.Zip.ZipFile zp = new Ionic.Zip.ZipFile();
                zp.AddFile("script.ist");
                zp.AddDirectory("res", "res");
                zp.Save($"{Filename}.sft");

                byte[]      fl = File.ReadAllBytes($"{Filename}.sft");
                byte[]      res;
                List <byte> tmplist = new List <byte>();
                foreach (byte tmp in fl)
                {
                    var vt = ~tmp;
                    tmplist.Add((byte)vt);
                }
                res = tmplist.ToArray();
                File.WriteAllBytes($"{Filename}.sft", res);
                File.Delete("script.ist");
                Directory.Delete("res", true);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"При загрузке .sft файла произошла ошибка \nОписаие ошибки:{ex.Message}");
            }
        }
Example #55
0
        /// <summary>
        /// zip when has special file
        /// </summary>
        /// <param name="fileToZips"></param>
        /// <param name="zipedFile"></param>
        /// <param name="basePath"></param>
        public static void ZipAdvanced(string[] fileToZips, string zipedFile, string basePath)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.GetEncoding(932)))
            {
                zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always;
                zip.CompressionLevel   = Ionic.Zlib.CompressionLevel.BestSpeed;
                zip.BufferSize         = 65536 * 8; // Set the buffersize to 512k for better efficiency with large files

                foreach (string fileToZip in fileToZips)
                {
                    if (LongPath.IsFileExists(fileToZip))
                    {
                        FileStream fs = LongPath.OpenForOnlyRead(fileToZip);
                        zip.AddEntry(fileToZip.Substring(basePath.Length), fs);

                        continue;
                    }

                    else //文件夹
                    {
                        if (Directory.Exists(fileToZip))
                        {
                            foreach (var e in Directory.EnumerateFiles(fileToZip, "*", SearchOption.AllDirectories))
                            {
                                try
                                {
                                    //判断文件名是否以空格结尾
                                    bool   spaceEnd = false;
                                    string name     = e.Substring(e.LastIndexOf('\\') + 1);
                                    if (name.TrimEnd().Length < name.Length)
                                    {
                                        spaceEnd = true;
                                    }
                                    if (!spaceEnd && File.Exists(e))
                                    {
                                        zip.AddFile(e, e.Substring(basePath.Length, e.LastIndexOf('\\') - basePath.Length));
                                    }
                                    else
                                    {
                                        string entryName = e.Substring(basePath.Length);

                                        /*
                                         * 末尾添加全角空格,(ps:如果同一目录下有个 文件a 又有一个文件 a空格 则解压时会同名冲突,故添加全角空格以区分
                                         */
                                        if (spaceEnd)
                                        {
                                            entryName += " ";
                                        }
                                        FileStream fs = LongPath.OpenForOnlyRead(e);
                                        zip.AddEntry(entryName, fs);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    logger.Error("path:" + e + Environment.NewLine + ex.Message);
                                }
                            }
                        }
                        else
                        {
                            foreach (String path in FilesystemHelper.EnumFilesYield(fileToZip))
                            {
                                try
                                {
                                    FileStream fs = LongPath.OpenForOnlyRead(path);
                                    zip.AddEntry(path.Substring(basePath.Length), fs);
                                }
                                catch (Exception ex)
                                {
                                    logger.Error("path:" + path + Environment.NewLine + ex.Message);
                                }
                            }
                        }
                    }
                }
                zip.Save();
            }
        }
Example #56
0
        //downloads Files that are not present in the Destination Server
        public void Downloadfile(string URL, string FileName, string user, string pass, string RowNumber, int Grid2RowNumber, string File_Size)
        {
            long   FileSize = 0;
            string UserName = user;               //User Name of the FTP server
            string Password = pass;               //Password of the FTP server

            string LocalDirectory = "C:\\Temp\\"; //Local directory where the files will be downloaded

            DateTime DT = DTPCheck.Value;

            //UpdateGrid2("Downloading File", Grid2RowNumber,2);

            try
            {
                //download code
                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }
                FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(new Uri(URL + FileName));
                requestFileDownload.Credentials = new NetworkCredential(UserName, Password);
                //requestFileDownload.Credentials = new NetworkCredential();
                requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
                Stream         responseStream       = responseFileDownload.GetResponseStream();
                FileStream     writeStream          = new FileStream(LocalDirectory + "/" + FileName, FileMode.Create);
                int            Length    = 2048;
                Byte[]         buffer    = new Byte[Length];
                int            bytesRead = responseStream.Read(buffer, 0, Length);
                lock (_object)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        //logs activity into Logs.Txt file
                        file.WriteLine("[" + DateTime.Now + "] " + "Downloading File from site to temp folder: " + FileName + " with a File Size of " + File_Size);
                        //logs activity into Textbox
                        UpdateStatusBar("[" + DateTime.Now + "] " + "Downloading File from site to temp folder: " + FileName + " with a File Size of " + File_Size + "");
                        //updates file activity into File List Grid
                        UpdateGrid2(0, Grid2RowNumber, 6);
                    }
                }
                // streams/downloads file from site to temp folder.
                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }

                while (bytesRead > 0)
                {
                    if (FileSize != 0)
                    {
                        UpdateGrid2(Convert.ToInt32((FileSize / double.Parse(File_Size) * 100)), Grid2RowNumber, 6);
                        //UpdateStatusBar("[" + DateTime.Now + "] " + FileName + " Downloaded: " + String.Format((FileSize / double.Parse(File_Size) * 100).ToString("00"), "0.00") + "");
                        //Thread.Sleep(1000);
                    }
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                    FileSize  = FileSize + bytesRead;
                }

                //logs activity in the Logs.Txt file.
                lock (_object)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] " + FileName + " Size Downloaded: " + (FileSize + Length));
                    }
                }

                //logs activity into Textbox
                UpdateStatusBar("[" + DateTime.Now + "] " + FileName + " Size Downloaded: " + (FileSize + Length) + "");

                responseStream.Close();
                writeStream.Close();


                requestFileDownload = null;
                // end of download code
                //********************************************************************************************

                //********************************************************************************************
                //start conversion protocol
                //********************************************************************************************
                lock (_object)
                {
                    UpdateGrid2(Convert.ToInt32(0), Grid2RowNumber, 7);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] File Conversion Started.");
                    }
                }
                String targetPath = @"C:\Temp\" + FileName.Substring(0, 8) + ".RNX";
                string sourceFile = System.IO.Path.Combine(@"C:\Temp\", FileName);
                string destFile   = System.IO.Path.Combine(targetPath, FileName);

                Directory.CreateDirectory(@"C:\Temp\" + FileName.Substring(0, 8) + ".RNX");
                File.Copy(sourceFile, destFile);

                RunTEQC(destFile, DateTime.Now.Year.ToString());

                File.Delete(destFile);

                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    if (CancelProg == true)
                    {
                        UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                        return;
                    }
                    String Target = targetPath + @"\" + FileName.Substring(0, 8) + "." + DateTime.Now.Year.ToString();
                    zip.CompressionLevel        = Ionic.Zlib.CompressionLevel.Default;
                    zip.SaveProgress           += (object sender, SaveProgressEventArgs e) => SaveProgress(sender, e, Grid2RowNumber);
                    zip.StatusMessageTextWriter = System.Console.Out;
                    zip.AddFile(Target + "g", "");
                    zip.AddFile(Target + "n", "");
                    zip.AddFile(Target + "o", "");
                    zip.Save(LocalDirectory + FileName.Substring(0, 8) + ".RNX.zip");
                }
                lock (_object)
                {
                    UpdateGrid2(Convert.ToInt32(100), Grid2RowNumber, 7);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] File Conversion Finished.");
                    }
                }
                //********************************************************************************************
                // calls the conversion protocol
                //********************************************************************************************

                //********************************************************************************************
                //compresses the download raw file.
                //********************************************************************************************
                lock (_object)
                {
                    UpdateGrid2(0, Grid2RowNumber, 8);
                }
                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }
                //logs activity
                lock (_object)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] " + "Compressing File");
                    }
                }
                //logs activity
                UpdateStatusBar("[" + DateTime.Now + "] " + "Compressing File" + "\r\n");
                //logs activity
                //UpdateGrid2("Compressing File", Grid2RowNumber, 2);
                //compression code
                String DirectoryToZip  = LocalDirectory + FileName;
                String ZipFileToCreate = LocalDirectory + FileName + ".zip";


                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    if (CancelProg == true)
                    {
                        UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                        return;
                    }
                    zip.CompressionLevel        = Ionic.Zlib.CompressionLevel.Default;
                    zip.SaveProgress           += (object sender, SaveProgressEventArgs e) => SaveProgress(sender, e, Grid2RowNumber);
                    zip.StatusMessageTextWriter = System.Console.Out;
                    zip.AddFile(DirectoryToZip, ""); // recurses subdirectories
                    zip.Save(ZipFileToCreate);
                }
                //logs activity
                lock (_object)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] " + "File Compression Finished");
                    }
                }
                //logs activity
                UpdateStatusBar("[" + DateTime.Now + "] " + "File Compression Finished" + "");
                lock (_object)
                {
                    UpdateGrid2(100, Grid2RowNumber, 8);
                }
                //********************************************************************************************
                // end of compression code
                //********************************************************************************************

                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }
                //********************************************************************************************
                //deletes the raw file in the temp folder
                //********************************************************************************************

                lock (_object)
                {
                    //file delete code
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        //logs activity
                        file.WriteLine("[" + DateTime.Now + "] " + "Deleting Raw & RNX File from Temp Folder");
                        //logs activity
                        UpdateStatusBar("[" + DateTime.Now + "] " + "Deleting Raw & RNX File from Temp Folder" + "");
                        //delete code/command
                        File.Delete(LocalDirectory + FileName);
                        Directory.Delete(LocalDirectory + FileName.Substring(0, 8) + ".RNX", true);
                        //logs activity
                        UpdateStatusBar("[" + DateTime.Now + "] " + "File Raw & RNX File Deletion Completed" + "");
                        //logs activity
                        file.WriteLine("[" + DateTime.Now + "] " + "File Raw & RNX File Deletion Completed");
                    }
                }

                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }
                //********************************************************************************************
                //end of deletion code
                //********************************************************************************************

                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }

                //********************************************************************************************
                //uploads the compress file into the ftp server
                //********************************************************************************************
                lock (_object)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] " + "File Uploading Started.");
                    }
                }
                string LocalDirectory1 = @"C:\Temp\" + FileName + ".zip";
                string LocalDirectory2 = @"C:\Temp\" + FileName.Substring(0, 8) + ".RNX.zip";
                //string User = this.textBox7.Text;
                //string Pass = this.textBox6.Text;
                //string BaseDirectory = this.textBox8.Text;

                //checks folders in the File server
                FolderChecker(currRow, File_Location, DTPCheck.Value);
                //checks folders in the RNX File Server
                FolderChecker(currRow, File_LocationRNX, DTPCheck.Value);

                string DestinationDirectory = (File_Location + DTPCheck.Value.Year.ToString()) + @"\" + DTPCheck.Value.Month.ToString("00")
                                              + @"\" + DTPCheck.Value.Day.ToString("00") +
                                              @"\" + Grid.Rows[int.Parse(RowNumber)].Cells[0].Value.ToString() + @"\"; //Local directory where the files will be uploaded/copied.

                string DestinationDirectory2 = (File_LocationRNX + DTPCheck.Value.Year.ToString()) + @"\" + DTPCheck.Value.Month.ToString("00")
                                               + @"\" + DTPCheck.Value.Day.ToString("00") +
                                               @"\" + Grid.Rows[int.Parse(RowNumber)].Cells[0].Value.ToString() + @"\"; //Local directory where the files will be uploaded/copied for the compressed RNX files

                NetworkCredential readCredentials = new NetworkCredential(@User_ID, Password_File);
                using (new NetworkConnection(File_Location.ToString(), readCredentials))
                {
                    PageNet_AutoDownloader.CustomFileCopier fc = new PageNet_AutoDownloader.CustomFileCopier(LocalDirectory1, DestinationDirectory + FileName + ".zip");
                    //fc.OnProgressChanged += filecopyprogress;
                    //fc.OnProgressChanged += filecopyprogress(Grid2RowNumber, Grid2RowNumber);
                    fc.OnProgressChanged += (double Persentage, ref bool Cancel) => filecopyprogress(Persentage, Grid2RowNumber, 9);
                    fc.OnComplete        += filecopycomplete;
                    fc.Copy();
                }

                using (new NetworkConnection(File_LocationRNX, readCredentials))
                {
                    PageNet_AutoDownloader.CustomFileCopier fc = new PageNet_AutoDownloader.CustomFileCopier(LocalDirectory2, DestinationDirectory2 + FileName.Substring(0, 8) + ".RNX.zip");
                    fc.OnProgressChanged += (double Persentage, ref bool Cancel) => filecopyprogress(Persentage, Grid2RowNumber, 9);
                    fc.OnComplete        += filecopycomplete;
                    fc.Copy();
                }
                //end of upload code
                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }
                lock (_object)
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        file.WriteLine("[" + DateTime.Now + "] " + "File Uploading Finished");
                    }
                }
                //deletes the zip file in the temp folder
                lock (_object)
                {
                    //file delete code
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@AppDomain.CurrentDomain.BaseDirectory + StrDate + "_Logs.txt", true))
                    {
                        //logs activity
                        file.WriteLine("[" + DateTime.Now + "] " + "Deleting File from Temp Folder");
                        //logs activity
                        UpdateStatusBar("[" + DateTime.Now + "] " + "Deleting File from Temp Folder" + "");
                        //delete code/command
                        File.Delete(LocalDirectory + FileName + ".zip");
                        File.Delete(LocalDirectory + FileName.Substring(0, 8) + ".RNX.zip");

                        //logs activity
                        UpdateStatusBar("[" + DateTime.Now + "] " + "File Deletion Completed" + "");
                        //logs activity
                        file.WriteLine("[" + DateTime.Now + "] " + "File Deletion Completed");
                    }
                }

                if (CancelProg == true)
                {
                    UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                    return;
                }
                // end of deletion code
                return;
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ConnectFailure)
                {
                    //if there is no connection to the site
                    UpdateStatusBar("[" + DateTime.Now + "] " + ex.Message.ToString() + "");
                    if (CancelProg == true)
                    {
                        UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                        return;
                    }
                }
                if (ex.Status == WebExceptionStatus.Timeout)
                {
                    if (DownCounter < 3)
                    {
                        //if the connection has a timeout
                        UpdateStatusBar("[" + DateTime.Now + "] " + ex.Message.ToString() + "");
                        UpdateStatusBar("[" + DateTime.Now + "] Retrying Download of file " + FileName + "");
                        //Update("[" + DateTime.Now + "] " + ex.Message.ToString() + "\r\n");
                        //Update("[" + DateTime.Now + "] Retrying Download of file " + FileName + "\r\n");
                        Downloadfile(URL, FileName, user, pass, RowNumber, Grid2RowNumber, File_Size);
                        DownCounter++;
                        if (CancelProg == true)
                        {
                            UpdateStatusBar("[" + DateTime.Now + "] " + "Process Stopped");
                            return;
                        }
                    }
                }
            }
        }
        public void AddEntries(Dictionary <string, FileInfo> files, string zipArchiveName, Ionic.Zlib.CompressionLevel level)
        {
            try
            {
                List <string> entryAdded   = new List <string>();
                List <string> entryDeleted = new List <string>();

                if (files.Count > 0)
                {
                    lock (_zipLock)
                    {
                        var filesToDelete = new List <string>();
                        //

                        using (var izip = new Ionic.Zip.ZipFile(zipArchiveName))
                        {
                            izip.CompressionLevel = level;
                            foreach (var keyValuePair in files)
                            {
                                try
                                {
                                    if (keyValuePair.Value.Exists)
                                    {
                                        ZipEntry e = izip.AddFile(keyValuePair.Value.FullName);

                                        e.FileName = keyValuePair.Key;
                                        entryAdded.Add(e.FileName);

                                        filesToDelete.Add(keyValuePair.Value.FullName);
                                    }
                                }
                                catch
                                {
                                    //
                                }
                            }

                            izip.Save();
                        }

                        foreach (var fileToDelete in filesToDelete)
                        {
                            try
                            {
                                System.IO.File.Delete(fileToDelete);
                                entryDeleted.Add(fileToDelete);
                            }
                            catch
                            {
                            }
                        }

                        FileInfo ziFileInfo = new FileInfo(zipArchiveName);

                        OnLogRotated(new ZipRotationPerformedEventArgs(zipArchiveName, entryAdded, entryDeleted, ziFileInfo.Length));
                    }
                }
            }
            catch /*(Exception exception)*/
            {
                //
            }
        }
        public void CreateZipFiles()
        {
            //Delete old zipfiles
            if (Directory.Exists(zipDirectory))
            {
                Directory.Delete(zipDirectory, true);
            }
            Directory.CreateDirectory(zipDirectory);

            //Create empty zipfiles
            using (ZipOutputStream zos = new ZipOutputStream(zipDirectory + "\\ClientFiles.zip"))
            { }
            using (ZipOutputStream zos = new ZipOutputStream(zipDirectory + "\\ServerFiles.zip"))
            { }

            //Create list of resourcepacks
            List <string> rpackList = new List <string>();

            using (FileStream fs = File.Open(cd + "\\resourcepack\\distribute.txt", FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while (true)
                    {
                        string nextLine = sr.ReadLine();

                        if (nextLine != null)
                        {
                            rpackList.Add(nextLine);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            //Create client zipfile
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipDirectory + "\\ClientFiles.zip"))
            {
                //Add modpack folders
                foreach (string folder in Directory.GetDirectories(cd + "\\modpack", "*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(folder))
                    {
                        zip.RemoveEntry(folder);
                    }
                    zip.AddDirectoryByName(folder.Replace(cd + "\\modpack", ""));
                }
                //Add resourcepacks
                foreach (string file in Directory.GetFiles(cd + "\\resourcepack", "*.zip", SearchOption.TopDirectoryOnly))
                {
                    if (rpackList.Contains(Path.GetFileName(file)))
                    {
                        if (zip.ContainsEntry(file))
                        {
                            zip.RemoveEntry(file);
                        }
                        zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\resourcepack", "resourcepacks"));
                    }
                }
                //Add modpack files
                foreach (string file in Directory.GetFiles(cd + "\\modpack", "*.*", SearchOption.AllDirectories))
                {
                    if ((Main.acces.includeOptionsBox.Checked || (!file.Contains("\\modpack\\options.txt") && !file.Contains("\\modpack\\optionsof.txt"))) && (Main.acces.includeDisabledBox.Checked || Path.GetExtension(file) != ".disabled") && file != cd + "\\modpack\\bin\\modpack.jar")
                    {
                        if (zip.ContainsEntry(file))
                        {
                            zip.RemoveEntry(file);
                        }
                        zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\modpack", ""));
                    }
                }

                //Add modpack.jar
                try
                {
                    string file      = cd + "\\plugins\\mergedjar\\modpack.jar";
                    string zipFolder = "bin";

                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, zipFolder);
                }
                catch
                { }
                //Add idfixminus.jar
                if (File.Exists(cd + "\\plugins\\idfixer\\idfixminus.jar"))
                {
                    string file      = cd + "\\plugins\\idfixer\\idfixminus.jar";
                    string zipFolder = "mods";

                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, zipFolder);
                }

                //Save zipfile
                bool succeed = false;
                while (!succeed)
                {
                    try
                    {
                        zip.Save();
                        succeed = true;
                    }
                    catch
                    { }
                }
            }

            //Create server zipfile
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zipDirectory + "\\ServerFiles.zip"))
            {
                //Add server folders
                foreach (string folder in Directory.GetDirectories(cd + "\\tests\\ServerBuild", "*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(folder))
                    {
                        zip.RemoveEntry(folder);
                    }
                    zip.AddDirectoryByName(folder.Replace(cd + "\\tests\\ServerBuild", ""));
                }
                //Add server files
                foreach (string file in Directory.GetFiles(cd + "\\tests\\ServerBuild", "*.*", SearchOption.AllDirectories))
                {
                    if (zip.ContainsEntry(file))
                    {
                        zip.RemoveEntry(file);
                    }
                    zip.AddFile(file, file.Replace(Path.GetFileName(file), "").Replace(cd + "\\tests\\ServerBuild", ""));
                }

                //Save zipfile
                bool succeed = false;
                while (!succeed)
                {
                    try
                    {
                        zip.Save();
                        succeed = true;
                    }
                    catch
                    { }
                }
            }
        }
Example #59
0
        private static bool compressFilesToZip()
        {
            if (Directory.Exists(destinationDirectory + "tmp"))
            {
                int segmentsCreated = 0;
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Encoding.UTF8))
                {
                    if (ZIPpartSizeMB <= 0)
                    {
                        zip.AddDirectory(destinationDirectory + "tmp");
                        zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");

                        zip.Save(destinationDirectory + ZIPfileSuffixName);

                        segmentsCreated = zip.NumberOfSegmentsForMostRecentSave;
                    }
                }

                if (ZIPpartSizeMB > 0)
                {
                    FileInfo[] files = GetFilesFromDir(destinationDirectory + "tmp", listOfAllowedExtensions);


                    double filesSize = 0;
                    int    part      = 0;
                    int    lastIndex = 0;

                    while (true)
                    {
                        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Encoding.UTF8))
                        {
                            if (lastIndex == files.Count())
                            {
                                segmentsCreated++;

                                break;
                            }

                            for (int i = lastIndex; i <= files.Count(); i++)
                            {
                                if (lastIndex == files.Count())
                                {
                                    part++;
                                    zip.Save(destinationDirectory + part + "_" + ZIPfileSuffixName);

                                    filesSize = 0;

                                    break;
                                }

                                FileInfo file = files[i];

                                if (file.Length / 1024 > ZIPpartSizeMB * 1024)
                                {
                                    zip.AddFile(file.FullName, "");

                                    filesSize += file.Length / 1024;
                                    lastIndex++;

                                    part++;
                                    zip.Save(destinationDirectory + part + "_" + ZIPfileSuffixName);

                                    filesSize = 0;

                                    break;
                                }


                                if ((ZIPpartSizeMB * 1024 > (filesSize + (file.Length / 1024)) && i < files.Count()))
                                {
                                    zip.AddFile(file.FullName, "");

                                    filesSize += file.Length / 1024;
                                    lastIndex++;
                                }
                                else
                                {
                                    part++;
                                    zip.Save(destinationDirectory + part + "_" + ZIPfileSuffixName);

                                    filesSize = 0;

                                    break;
                                }
                            }
                        }
                    }
                }

                if (segmentsCreated > 0)
                {
                    try
                    {
                        DeleteDirectory(destinationDirectory + "tmp");
                    } catch (IOException ioex)
                    {
                    }

                    return(true);
                }
            }

            return(false);
        }
Example #60
-1
// ---------------------------------------------------------------------------    
    public override void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        HtmlMovies2 movies = new HtmlMovies2();
        // create a StyleSheet
        StyleSheet styles = new StyleSheet();
        styles.LoadTagStyle("ul", "indent", "10");
        styles.LoadTagStyle("li", "leading", "14");
        styles.LoadStyle("country", "i", "");
        styles.LoadStyle("country", "color", "#008080");
        styles.LoadStyle("director", "b", "");
        styles.LoadStyle("director", "color", "midnightblue");
        movies.SetStyles(styles);
        // create extra properties
        Dictionary<String,Object> map = new Dictionary<String, Object>();
        map.Add(HTMLWorker.FONT_PROVIDER, new MyFontFactory());
        map.Add(HTMLWorker.IMG_PROVIDER, new MyImageFactory());
        movies.SetProviders(map);
        // creates HTML and PDF (reusing a method from the super class)
        byte[] pdf = movies.CreateHtmlAndPdf(stream);
        zip.AddEntry(HTML, movies.Html.ToString());
        zip.AddEntry(RESULT1, pdf);
        zip.AddEntry(RESULT2, movies.CreatePdf());
        // add the images so the static html file works
        foreach (Movie movie in PojoFactory.GetMovies()) {
          zip.AddFile(
            Path.Combine(
              Utility.ResourcePosters, 
              string.Format("{0}.jpg", movie.Imdb)
            ), 
            ""
          );
        }
        zip.Save(stream);             
      }
    }