Save() публичный Метод

Saves the Zip archive to a file, specified by the Name property of the ZipFile.

The ZipFile instance is written to storage, typically a zip file in a filesystem, only when the caller calls Save. In the typical case, the Save operation writes the zip content to a temporary file, and then renames the temporary file to the desired name. If necessary, this method will delete a pre-existing file before the rename.

The ZipFile.Name property is specified either explicitly, or implicitly using one of the parameterized ZipFile constructors. For COM Automation clients, the Name property must be set explicitly, because COM Automation clients cannot call parameterized constructors.

When using a filesystem file for the Zip output, it is possible to call Save multiple times on the ZipFile instance. With each call the zip content is re-written to the same output file.

Data for entries that have been added to the ZipFile instance is written to the output when the Save method is called. This means that the input streams for those entries must be available at the time the application calls Save. If, for example, the application adds entries with AddEntry using a dynamically-allocated MemoryStream, the memory stream must not have been disposed before the call to Save. See the property for more discussion of the availability requirements of the input stream for an entry, and an approach for providing just-in-time stream lifecycle management.

/// Thrown if you haven't specified a location or stream for saving the zip, /// either in the constructor or by setting the Name property, or if you try /// to save a regular zip archive to a filename with a .exe extension. /// /// Thrown if is non-zero, and the number /// of segments that would be generated for the spanned zip file during the /// save operation exceeds 99. If this happens, you need to increase the /// segment size. ///
public Save ( ) : void
Результат void
Пример #1
0
		public string CreateArchiveWithFiles(IEnumerable<Guid> files, string serverDirectoryPath, string userName, string archiveName)
		{
			string path = string.Format("{0}{1}\\{2}\\", serverDirectoryPath, _temp, userName);
			if (Directory.Exists(path))
			{
				Directory.Delete(path, true);
			}
			Directory.CreateDirectory(path);
			var fullPath = string.Format("{0}{1}", path, archiveName);

			using (var archive = new ZipFile(fullPath))
			{
				foreach (var file in files)
				{
					var document = _documentService.GetDocumentInfo(file);
					var documentBytes = _documentService.GetDocument(file);
					archive.AddEntry(document.Name, documentBytes);
					archive.Save();
				}

				archive.Save();
			}

			return fullPath;
		}
Пример #2
0
        static void Main(string[] args)
        {
            var a = new Arguments(args);
            using (var z = new ZipFile())
            {
                Console.WriteLine("Compiling... ");

                switch (a["target"])
                {
                    case "plugin":
                        compilePlugin(a, z);

                        z.Save(new DirectoryInfo(a["path"]).Parent.FullName + "\\" + a["output"]);

                        break;
                    case "library":
                        compileLibrary(a, z);

                        z.Save(a["sources"] + "\\" + a["output"]);

                        break;
                }

            }

            Console.WriteLine("Done");
        }
Пример #3
0
        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);
        }
Пример #4
0
        public bool CreatePackage(string filename, bool includeWalkthrough, out string error, IEnumerable<WorldModel.PackageIncludeFile> includeFiles, Stream outputStream)
        {
            error = string.Empty;

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

                using (ZipFile zip = new ZipFile())
                {
                    zip.AddEntry("game.aslx", data, Encoding.UTF8);

                    if (includeFiles == null)
                    {
                        var fileTypesToInclude = m_worldModel.Game.Fields[FieldDefinitions.PublishFileExtensions] ??
                                             "*.jpg;*.jpeg;*.png;*.gif;*.js;*.wav;*.mp3;*.htm;*.html;*.svg";

                        foreach (var file in m_worldModel.GetAvailableExternalFiles(fileTypesToInclude))
                        {
                            zip.AddFile(Path.Combine(baseFolder, file), "");
                        }
                    }
                    else
                    {
                        foreach (var file in includeFiles)
                        {
                            zip.AddEntry(file.Filename, file.Content);
                        }
                    }

                    AddLibraryResources(zip, baseFolder, ElementType.Javascript);
                    AddLibraryResources(zip, baseFolder, ElementType.Resource);

                    if (filename != null)
                    {
                        zip.Save(filename);
                    }
                    else if (outputStream != null)
                    {
                        zip.Save(outputStream);
                    }
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }

            return true;
        }
Пример #5
0
        private void File_zip_Click_1(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtfile.Text))
            {
                MessageBox.Show("Please select a proper file", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtfile.Focus();
                return;
            }
            string filename = txtfile.Text;
            Thread thread   = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    FileInfo fi = new FileInfo(filename);
                    zip.AddFile(filename);
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filename);
                    zip.SaveProgress          += Zip_fileSaveProgress;
                    zip.Save(string.Format("{0}/{1}.zip", di.Parent.FullName, di.Name));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
Пример #6
0
        private void btnZipFolder_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFolder.Text))
            {
                MessageBox.Show("Please, select your folder", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtFolder.Focus();
                return;
            }
            string path   = txtFolder.Text;
            Thread thread = new Thread(t =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    zip.AddDirectory(path);
                    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
                    zip.SaveProgress          += Zip_SaveProgress;
                    zip.Save(string.Format("{0}{1}.zip", di.Parent.FullName, di.Name));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
Пример #7
0
 /// <summary>
 /// ZIP komprimiert den Inhalt des übergebenen Verzeichnisses in die übergebene Datei.
 /// </summary>
 /// <param name="directory"></param>
 /// <param name="targetFilePath"></param>
 public void CompressDirContentTo(string directory, string targetFilePath)
 {
     using (var zip = new Ionic.Zip.ZipFile()) {
         zip.AddDirectory(directory, "");
         zip.Save(targetFilePath);
     }
 }
Пример #8
0
        private void DosyaZiple(string dosyayolu, string dosyaadi, string DbName)
        {
            ManualResetEvent syncEvent = new ManualResetEvent(false);

            string DosyaAdiveYolu = dosyayolu + "\\" + dosyaadi;

            lbl_DBName.Text = DosyaAdiveYolu.ToString();

            Thread thread = new Thread(T =>
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                {
                    FileInfo Fi            = new FileInfo(DosyaAdiveYolu);
                    zip.UseZip64WhenSaving = Zip64Option.Always;
                    zip.AddFile(DosyaAdiveYolu);
                    DirectoryInfo di  = new DirectoryInfo(DosyaAdiveYolu);
                    zip.SaveProgress += Zip_SaveProccess;
                    zip.Save(string.Format("{0}/{1}.zip", di.Parent.FullName, di.Name));
                }
            })
            {
                IsBackground = true
            };

            thread.Start();
            thread.Join();
        }
Пример #9
0
        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);
        }
Пример #10
0
        /// <summary>
        /// 压缩zip
        /// </summary>
        /// <param name="fileToZips">文件路径集合</param>
        /// <param name="zipedFile">想要压成zip的文件名</param>
        public static void ZipOld(string[] fileToZips, string zipedFile)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipedFile, Encoding.UTF8))
            {
                List <string> pathlist = new List <string>();
                foreach (string fileToZip in fileToZips)
                {
                    if (System.IO.File.Exists(fileToZip))
                    {
                        using (FileStream fs = new FileStream(fileToZip, FileMode.Open, FileAccess.Read))
                        {
                            byte[] buffer = new byte[fs.Length];
                            fs.Read(buffer, 0, buffer.Length);
                            string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
                            string filePath = fileToZip.Substring(0, fileToZip.LastIndexOf("\\"));

                            if (!pathlist.Exists(x => x.Equals(filePath)))
                            {
                                pathlist.Add(filePath);
                                zip.AddDirectoryByName(filePath);
                            }
                            zip.AddFile(fileToZip, filePath);
                        }
                    }
                    if (System.IO.Directory.Exists(fileToZip))
                    {
                        string filePath = fileToZip.Substring(fileToZip.IndexOf("\\") + 1);
                        zip.AddDirectoryByName(filePath);
                        zip.AddDirectory(fileToZip, filePath);
                        //ZipFileDictory(fileToZip, "", zip);
                    }
                }
                zip.Save();
            }
        }
Пример #11
0
        public async Task <IActionResult> DownloadZip()
        {
            DirectoryInfo dir      = new DirectoryInfo(_folder);
            var           files    = dir.GetFiles();
            string        rootPath = AppDomain.CurrentDomain.BaseDirectory;
            var           bytes    = default(byte[]);


            using (var zip = new Ionic.Zip.ZipFile())
            {
                zip.Password = "******";
                foreach (var i in files)
                {
                    zip.AddFile(i.FullName, ".\\1.jpg").FileName = Guid.NewGuid() + ".jpg";                //第二個欄位是zip內的目錄
                }


                using (var ms = new MemoryStream())
                {
                    zip.Save(ms);
                    bytes = ms.ToArray();

                    return(File(bytes, "application/zip"));
                }
            }
        }
Пример #12
0
        public void Save()
        {
            //archive.UpdateEntry(name, Document.ToString());
            //using (var stream = entry.Open())
            //{
            //    stream.Seek(0, SeekOrigin.End);
            //    using (var sw = new StreamWriter(stream))
            //    {
            //        sw.Write(Document.ToString());
            //        sw.Flush();
            //    }
            //}
            var path = AppDomain.CurrentDomain.BaseDirectory + "temp.xml";

            Document.Save(path);
            archive.RemoveEntry(entry);
            archive.AddEntry(name, new FileStream(path, FileMode.Open));
            archive.Save();
            //using (var s = new MemoryStream())
            //{
            //    using (var sw = new StreamWriter(s))
            //    {
            //        var xml = Document.ToString();
            //        sw.WriteLine("123");
            //        sw.Flush();
            //        archive.AddEntry("test.xml", s);
            //        archive.Save();
            //    }
            //    //Document.Save(s);

            //}
        }
Пример #13
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();
        }
    }
Пример #14
0
 /// <summary>
 /// 压缩文件
 /// </summary>
 /// <param name="toDirectory">压缩到该目录</param>
 /// <param name="toFileName">压缩文件名,不带扩展名,自动添加.zip扩展名</param>
 public void Compress( string toDirectory, string toFileName ) {
     using ( var zip = new ZipFile() ) {
         zip.Password = _password;
         AddFiles( zip );
         zip.Save( GetFilePath( toDirectory, toFileName ) );
     }
 }
Пример #15
0
 /// <summary>
 /// Append the zip data to the file-entry specified.
 /// </summary>
 /// <param name="path"></param>
 /// <param name="entry"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 public static bool ZipCreateAppendData(string path, string entry, string data)
 {
     try
     {
         if (File.Exists(path))
         {
             using (var zip = ZipFile.Read(path))
             {
                 zip.AddEntry(entry, data);
                 zip.Save();
             }
         }
         else
         {
             using (var zip = new ZipFile(path))
             {
                 zip.AddEntry(entry, data);
                 zip.Save();
             }
         }
     }
     catch (Exception err)
     {
         Log.Error(err);
         return(false);
     }
     return(true);
 }
Пример #16
0
 public void Comprimir()
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) {
         zip.AddFile("transacoes.csv");
         zip.Save("banco_de_dados.zip");
     }
 }
Пример #17
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);
            }
        }
Пример #18
0
        public bool Upload(out Exception e)
        {
            try
            {
                string fileToUpload = IsTerrainPng ? TerrainGenerator.Output : _baseZip;
                if (!IsTerrainPng)
                {
                    using (ZipFile zip = new ZipFile(fileToUpload))
                    {
                        zip.RemoveEntry("terrain.png");
                        zip.AddFile(TerrainGenerator.Output);
                        zip.Save();
                    }
                }
                int    name = new Random().Next();
                string ext  = IsTerrainPng ? ".png" : ".zip";
                URL = $"http://gemz.christplay.x10host.com/textures/{name}{ext}";
                byte[] res = FileUploading.UploadFile(
                    $"http://gemz.christplay.x10host.com/texture.php?new={name}{ext}",
                    fileToUpload);

                e = null;
                return(true);
            }
            catch (Exception exception)
            {
                e = exception;
                return(false);
            }
        }
Пример #19
0
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // use one of the previous examples to create a PDF
      MovieTemplates mt = new MovieTemplates();
      // Create a reader
      byte[] pdf = Utility.PdfBytes(mt);
      PdfReader reader = new PdfReader(pdf);
      // loop over all the pages in the original PDF
      int n = reader.NumberOfPages;      
      using (ZipFile zip = new ZipFile()) {
        for (int i = 0; i < n; ) {
          string dest = string.Format(RESULT, ++i);
          using (MemoryStream ms = new MemoryStream()) {
// We'll create as many new PDFs as there are pages
            // step 1
            using (Document document = new Document()) {
              // step 2
              using (PdfCopy copy = new PdfCopy(document, ms)) {
                // step 3
                document.Open();
                // step 4
                copy.AddPage(copy.GetImportedPage(reader, i));
              }
            }
            zip.AddEntry(dest, ms.ToArray());
          }
        }
        zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
        zip.Save(stream);       
      }
    }
Пример #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;
     }
 }
        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 )
            {

            }
        }
Пример #22
0
        public void ArchiveTo(string pathTo, string password)
        {
            using (var zip = new DotZip.ZipFile())
            {
                if (!string.IsNullOrEmpty(password))
                {
                    zip.Password   = password;
                    zip.Encryption = DotZip.EncryptionAlgorithm.WinZipAes256;
                }

                string rootDir = new DirectoryInfo(Data.Path).Name;

                var files = Directory.GetFiles(Data.Path, "*", SearchOption.AllDirectories);
                foreach (var currFile in files)
                {
                    string currDir      = Path.GetDirectoryName(currFile);
                    string relativePath = currDir.Length > Data.Path.Length ? currDir.Substring(Data.Path.Length + 1) : "";
                    if (string.IsNullOrEmpty(relativePath))
                    {
                        relativePath = rootDir;
                    }
                    else
                    {
                        relativePath = rootDir + "\\" + relativePath;
                    }

                    zip.AddFile(currFile, relativePath);
                }

                zip.Save(pathTo);
            }
        }
        public string CreateSolution(IBuildBootstrappedSolutions bootstrapper, SolutionConfiguration configuration)
        {
            configuration.InCodeSubscriptions = true;
            foreach (var endpointConfiguration in configuration.EndpointConfigurations)
            {
                endpointConfiguration.InCodeSubscriptions = configuration.InCodeSubscriptions;
            }

            var solutionData = bootstrapper.BootstrapSolution(configuration);

            var solutionDirectory = SavePath + Guid.NewGuid();

            var solutionFile = SaveSolution(solutionDirectory, solutionData);

            InstallNuGetPackages(solutionDirectory, solutionData, solutionFile, NuGetExe);

            //AddReferencesToNugetPackages(solutionDirectory);

            var zipFilePath = solutionFile.Replace(".sln", ".zip");

            using (var zip = new ZipFile())
            {
                zip.AddDirectory(solutionDirectory, "Solution");
                zip.Save(zipFilePath);
            }

            return zipFilePath;
        }
Пример #24
0
 public static String extractIPA(IPAInfo info)
 {
     using (ZipFile ipa = ZipFile.Read(info.Location))
     {
         Debug("IPALocation: " + info.Location);
         Debug("Payload location: " + info.BinaryLocation);
         foreach (ZipEntry e in ipa)
         {
             //Debug ("file:" + e.FileName);
             if (e.FileName.Contains(".sinf") || e.FileName.Contains(".supp"))
             {
                 //extract it
                 Debug(GetTemporaryDirectory());
                 e.Extract(GetTemporaryDirectory(), ExtractExistingFileAction.OverwriteSilently);
             }
             else if (e.FileName == info.BinaryLocation)
             {
                 Debug("found binary!!");
                 e.Extract(GetTemporaryDirectory(), ExtractExistingFileAction.OverwriteSilently);
             }
         }
     }
     //zip!
     String AppDirectory = Path.Combine(GetTemporaryDirectory(), "Payload");
     Debug("AppDirectory: " + AppDirectory);
     //return null;
     String ZipPath = Path.Combine(GetTemporaryDirectory(), "upload.ipa");
     using (ZipFile zip = new ZipFile())
     {
         zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;
         zip.AddDirectory(AppDirectory);
         zip.Save(ZipPath);
     }
     return ZipPath;
 }
Пример #25
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);
      }              
    }
Пример #26
0
    private static void CollectLogFiles(string dataPath, string outputPath, List<string> products)
    {
      if (!Directory.Exists(outputPath))
        Directory.CreateDirectory(outputPath);

      string targetFile = string.Format("MediaPortal2-Logs-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH.mm.ss"));
      targetFile = Path.Combine(outputPath, targetFile);
      if (File.Exists(targetFile))
        File.Delete(targetFile);

      ZipFile archive = new ZipFile(targetFile);
      foreach (var product in products)
      {
        string sourceFolder = Path.Combine(dataPath, @"Team MediaPortal", product, "Log");
        if (!Directory.Exists(sourceFolder))
        {
          Console.WriteLine("Skipping non-existant folder {0}", sourceFolder);
          continue;
        }
        Console.WriteLine("Adding folder {0}", sourceFolder);
        try
        {
          archive.AddDirectory(sourceFolder, product);
        }
        catch (Exception ex)
        {
          Console.WriteLine("Error adding folder {0}: {1}", sourceFolder, ex);
        }
      }
      archive.Save();
      archive.Dispose();
      Console.WriteLine("Successful created log archive: {0}", targetFile);

      Process.Start(outputPath); // Opens output folder
    }
Пример #27
0
        public FileResult batchDownload(string runids)
        {
            List <string> filepaths = new List <string>();

            foreach (string runid in runids.Split(","))
            {
                filepaths.Add(_context.getRawPath(Convert.ToInt32(runid.Split("-")[1])).Replace("json", "txt"));
            }

            //filepaths.Add(@"C:\Users\griff\Downloads\RUN_20191223_164427_CP53.json");

            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                zip.AddDirectoryByName("runs");
                foreach (string filepath in filepaths)
                {
                    zip.AddFile(filepath, "runs");
                }
                string zipName = String.Format("RawArchive_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    zip.Save(memoryStream);
                    return(File(memoryStream.ToArray(), "application/zip", zipName));
                }
            }
        }
Пример #28
0
        internal static void CreateZipFile(this SolutionInfo si)
        {
            using (var zip = new ZipFile())
            {
                zip.AddDirectory(si.TempPath);
                var zipDirectory = Program.Options.ZipDirectory;

                // No ZipDirectory provided
                if (string.IsNullOrWhiteSpace(zipDirectory))
                {
                    // Default to the parent folder of the solution
                    zipDirectory = Path.GetFullPath(Path.Combine(si.Directory, ".."));
                    if (!Directory.Exists(zipDirectory))
                    {
                        // No parent folder then use the solution directory
                        zipDirectory = si.Directory;
                    }
                }

                var zipName = Path.Combine(zipDirectory, si.Name + ".zip");
                zip.Save(zipName);
                CommandLine.WriteLineColor(ConsoleColor.Yellow, "Created zip file {0}", zipName);
                si.TempPath.Delete();
            }
        }
Пример #29
0
		public byte[] GetArchivedFiles(IEnumerable<Guid> files)
		{
			using (var ms = new MemoryStream())
			{
				using (var zip = new ZipFile())
				{
					foreach (var id in files)
					{
						var documentInfo = _documentService.GetDocumentInfo(id);
						var documentBytes = _documentService.GetDocument(id);

						if (documentInfo.IsEncrypted)
						{
							documentBytes = _cryptographicProvider.Decrypt(documentBytes).Value;
						}
						string dateString = documentInfo.DateAdded.ToString("MM.dd.yyyy_hh.mmtt", CultureInfo.InvariantCulture);
						string fileName = String.Format("{0}_{1}{2}", documentInfo.Name, dateString, documentInfo.DocumentType);
						zip.AddEntry(fileName, documentBytes);
					}

					zip.Save(ms);
					ms.Position = 0;

					return ms.ToArray();
				}
			}
		}
Пример #30
0
// ---------------------------------------------------------------------------    
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        // Use previous examples to create PDF files
        MovieLinks1 m = new MovieLinks1(); 
        byte[] pdfM = Utility.PdfBytes(m);
        LinkActions l = new LinkActions();
        byte[] pdfL = l.CreatePdf();
        // Create readers.
        PdfReader[] readers = {
          new PdfReader(pdfL),
          new PdfReader(pdfM)
        };
        
        // step 1
        //Document document = new Document();
        // step 2
        using (var ms = new MemoryStream()) { 
          // step 1
          using (Document document = new Document()) {
            using (PdfCopy copy = new PdfCopy(document, ms)) {
              // step 3
              document.Open();
              // step 4
              int n;
              // copy the pages of the different PDFs into one document
              for (int i = 0; i < readers.Length; i++) {
                readers[i].ConsolidateNamedDestinations();
                n = readers[i].NumberOfPages;
                for (int page = 0; page < n; ) {
                  copy.AddPage(copy.GetImportedPage(readers[i], ++page));
                }
              }
              // Add named destination  
              copy.AddNamedDestinations(
                // from the second document
                SimpleNamedDestination.GetNamedDestination(readers[1], false),
                // using the page count of the first document as offset
                readers[0].NumberOfPages
              );
            }
            zip.AddEntry(RESULT1, ms.ToArray());
          }
          
          // Create a reader
          PdfReader reader = new PdfReader(ms.ToArray());
          // Convert the remote destinations into local destinations
          reader.MakeRemoteNamedDestinationsLocal();
          using (MemoryStream ms2 = new MemoryStream()) {
            // Create a new PDF containing the local destinations
            using (PdfStamper stamper = new PdfStamper(reader, ms2)) {
            }
            zip.AddEntry(RESULT2, ms2.ToArray());
          }
          
        }
        zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM);
        zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL);
        zip.Save(stream);             
      }   
   }
Пример #31
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"));
        }
Пример #32
0
    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
    }
Пример #33
0
        static void CompressBackups()
        {
            backupArchive = new IZ.ZipFile(
                String.Format("{0}\\menumate-backup-{1}.zip",
                              creationCacheDirectory.FullName,
                              backupTime));
            IEnumerable <FileInfo> files =
                creationCacheDirectory.EnumerateFiles("*.fbk");

            SCLP.LogProxy.Log(SCLP.LogLevel.Info,
                              String.Format(
                                  "Archiving backup to {0} for transit...",
                                  backupArchive.Name));

            backupArchive.SaveProgress +=
                ZipSaveCompletionHandler;

            foreach (FileInfo f in files)
            {
                SCLP.LogProxy.Log(SCLP.LogLevel.Info,
                                  String.Format(
                                      "Archiving {0} ...", f.FullName));
                backupArchive.AddFile(f.FullName, "");
            }

            backupArchive.Save();
            SCLP.LogProxy.Log(SCLP.LogLevel.Info, "Archive built.");
        }
Пример #34
0
// ---------------------------------------------------------------------------        
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) { 
        byte[] pdf = new Superimposing().CreatePdf();
        // Create a reader
        PdfReader reader = new PdfReader(pdf);
        using (MemoryStream ms = new MemoryStream()) {     
          // step 1
          using (Document document = new Document(PageSize.POSTCARD)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContent;
            PdfImportedPage page;
            for (int i = 1; i <= reader.NumberOfPages; i++) {
              page = writer.GetImportedPage(reader, i);
              canvas.AddTemplate(page, 1f, 0, 0, 1, 0, 0);
            }
          } 
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.AddEntry(SOURCE, pdf);
        zip.Save(stream);            
      }        
    }
Пример #35
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);             
      }
    }
Пример #36
0
        public static int Main(string[] args)
        {
            var options = new Options();

            if (!ParseCommandLineOptions(args, options))
                return 1;

            if (options.OutputDir == null)
                options.OutputDir = options.PackageDir;

            if (!Directory.Exists(options.OutputDir))
                Directory.CreateDirectory(options.OutputDir);

            var packageDllName = options.PackageName + ".dll";
            var packageArchiveName = options.PackageName + ".0.0.0.fld";
            var packageDllPath = Path.Combine(options.PackageDir, packageDllName);
            var packageArchivePath = Path.Combine(options.OutputDir, packageArchiveName);

            //Generate RPC classes
            if (!RemotingGen.Program.Generate(packageDllPath, options.PackageDir, false))
                return 1;

            //Create an archive
            using (var zip = new ZipFile())
            {
                zip.AddDirectory(options.PackageDir, "");
                zip.Save(packageArchivePath);
            }

            return 0;
        }
Пример #37
0
		void OnTestIonicZip()
		{
			var buffer = new byte[917504];
			foreach (var i in buffer)
			{
				buffer[i] = (byte)'a';
			}

			using (var zippedStream = new MemoryStream())
			{
				using (var zip = new ZipFile(Encoding.UTF8))
				{
					// uncommenting the following line can be used as a work-around
					// zip.ParallelDeflateThreshold = -1;
					zip.AddEntry("entry.txt", buffer);
					zip.Save(zippedStream);
				}
				zippedStream.Position = 0;

				using (var zip = ZipFile.Read(zippedStream))
				{
					using (var ms = new MemoryStream())
					{
						// This line throws a BadReadException
						zip.Entries.First().Extract(ms);
					}
				}
			}
		}
Пример #38
0
 // ---------------------------------------------------------------------------
 public void Write(Stream stream)
 {
     // Use old example to create PDF
     MovieTemplates mt = new MovieTemplates();
     byte[] pdf = Utility.PdfBytes(mt);
     using (ZipFile zip = new ZipFile())
     {
         using (MemoryStream ms = new MemoryStream())
         {
             // step 1
             using (Document document = new Document())
             {
                 // step 2
                 PdfWriter writer = PdfWriter.GetInstance(document, ms);
                 // step 3
                 document.Open();
                 // step 4
                 PdfPTable table = new PdfPTable(2);
                 PdfReader reader = new PdfReader(pdf);
                 int n = reader.NumberOfPages;
                 PdfImportedPage page;
                 for (int i = 1; i <= n; i++)
                 {
                     page = writer.GetImportedPage(reader, i);
                     table.AddCell(Image.GetInstance(page));
                 }
                 document.Add(table);
             }
             zip.AddEntry(RESULT, ms.ToArray());
         }
         zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
         zip.Save(stream);
     }
 }
        public void ImportActionShouldAddTestsToProblemIfZipFileIsCorrect()
        {
            var zipFile = new ZipFile();

            var inputTest = "input";
            var outputTest = "output";

            zipFile.AddEntry("test.001.in.txt", inputTest);
            zipFile.AddEntry("test.001.out.txt", outputTest);

            var zipStream = new MemoryStream();
            zipFile.Save(zipStream);
            zipStream = new MemoryStream(zipStream.ToArray());

            this.File.Setup(x => x.ContentLength).Returns(1);
            this.File.Setup(x => x.FileName).Returns("file.zip");
            this.File.Setup(x => x.InputStream).Returns(zipStream);

            var redirectResult = this.TestsController.Import("1", this.File.Object, false, false) as RedirectToRouteResult;
            Assert.IsNotNull(redirectResult);

            Assert.AreEqual("Problem", redirectResult.RouteValues["action"]);
            Assert.AreEqual(1, redirectResult.RouteValues["id"]);

            var tests = this.Data.Problems.All().First(pr => pr.Id == 1).Tests.Count;
            Assert.AreEqual(14, tests);

            var tempDataHasKey = this.TestsController.TempData.ContainsKey(GlobalConstants.InfoMessage);
            Assert.IsTrue(tempDataHasKey);

            var tempDataMessage = this.TestsController.TempData[GlobalConstants.InfoMessage];
            Assert.AreEqual("Тестовете са добавени към задачата", tempDataMessage);
        }
 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);
 }
Пример #41
0
 public void FolderToZip(string sourceDir, string path)
 {
     using (var surveyBackup = new ZipFile()) {
         surveyBackup.AddDirectory(sourceDir);
         surveyBackup.Save(path);
     }
 }
Пример #42
0
        public FileResult GetPages()
        {
            if (Request.Url != null)
            {
                var zip = new ZipFile();
                zip.AddDirectoryByName("Content");
                zip.AddDirectory(Server.MapPath("~/Content/"), "Content");
                var paths = DtoHelper.GetPaths();
                foreach (var path in paths)
                {
                    var url = Url.Action(path.Action, path.Controller, null, Request.Url.Scheme);
                    if (url != null)
                    {
                        var request = WebRequest.Create(string.Concat(url, Constants.Resources.DownloadParameter));
                        request.Credentials = CredentialCache.DefaultCredentials;
                        var response = (HttpWebResponse)request.GetResponse();
                        var dataStream = response.GetResponseStream();
                        {
                            if (dataStream != null)
                            {
                                zip.AddEntry(path.FileName, dataStream);
                            }
                        }
                    }
                }
                var stream = new MemoryStream();
                zip.Save(stream);
                stream.Position = 0;
                return new FileStreamResult(stream, "application/zip") { FileDownloadName = Constants.Resources.DownloadName };

            }
            return null;
        }
Пример #43
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;
        }
Пример #44
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();
    }
Пример #45
0
 public static void CreateFromDirectory(string directory, string targetZip)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.AddDirectory(directory);
         zip.Save(targetZip);
     }
 }
 public static void Zip(string Folder, string ZipFile)
 {
     using (Ionic.Zip.ZipFile zipFiles = new Ionic.Zip.ZipFile())
     {
         zipFiles.AddDirectory(Folder);
         zipFiles.Save(ZipFile);
     }
 }
Пример #47
0
 public static void ZipDirectory(string dirOnDisk, string dirPathInArchive, string zipPath)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.AddDirectory(dirOnDisk, dirPathInArchive);
         zip.Save(zipPath);
     }
 }
Пример #48
0
 public static void CreateFromDirectory(string sourceFolder, string archiveFileName)
 {
     using (var zipFile = new Ionic.Zip.ZipFile(Encoding.UTF8))
     {
         zipFile.AddDirectory(sourceFolder);
         zipFile.Save(archiveFileName);
     }
 }
Пример #49
0
 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);
 }
Пример #50
0
 public static void CreateFromDirectory(string directory, string targetZip)
 {
     using (var zip = new Ionic.Zip.ZipFile())
     {
         zip.UseZip64WhenSaving = Zip64Option.AsNecessary;
         zip.AddDirectory(directory);
         zip.Save(targetZip);
     }
 }
Пример #51
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
            }
Пример #52
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
            }
Пример #53
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);
            }
        }
Пример #54
0
 /// <summary>
 /// 压缩文件
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="save"></param>
 public static void Compress(string[] filename, string save, string dir = "", Encoding encoding = default(Encoding))
 {
     if (encoding == default(Encoding))
     {
         encoding = Encoding.Default;
     }
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
     {
         zip.AddFiles(filename, dir);
         zip.Save(save);
     }
 }
Пример #55
0
 public static void CompressDir(string dirctoryname, string save, Encoding encoding = default(Encoding))
 {
     if (encoding == default(Encoding))
     {
         encoding = Encoding.Default;
     }
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(encoding))
     {
         zip.AddDirectory(dirctoryname);
         zip.Save(save);
     }
 }
Пример #56
0
        private void do_BackUp()
        {
            try
            {
                //Backup bkpDBFull = new Backup();
                //bkpDBFull.Action = BackupActionType.Database;
                //bkpDBFull.Database = AppMain.SqlConnection.Database;
                //bkpDBFull.Devices.AddDevice("@"+(string)btnPath.EditValue, DeviceType.File);
                //bkpDBFull.BackupSetName = Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Millisecond);
                //bkpDBFull.BackupSetDescription = "MspDataBase";
                //bkpDBFull.Initialize = false;
                //Server server = new Server(AppMain.SqlConnection.Server);
                //bkpDBFull.SqlBackup(server);

                string filePath = BuildBackupPathWithFilename(AppMain.SqlConnection.Database);
                using (var connection = new SqlConnection(AppMain.SqlConnection.Connection()))
                {
                    var query = String.Format("BACKUP DATABASE [{0}] TO DISK='{1}'", AppMain.SqlConnection.Database, filePath);
                    using (var command = new SqlCommand(query, connection))
                    {
                        connection.Open();
                        command.ExecuteNonQuery();
                    }

                    Thread thread = new Thread(t =>
                    {
                        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
                        {
                            FileInfo fi = new FileInfo(filePath);
                            System.IO.DirectoryInfo di = new DirectoryInfo(filePath);
                            zip.SaveProgress          += Zip_SaveProgress;
                            zip.Save(string.Format("{0}{1}.zip", di.Parent.FullName, fi.Name));
                        }
                    })
                    {
                        IsBackground = true
                    };
                    thread.Start();


                    Log(AppMain.SqlConnection.Database + " veritabanı yedeklendi. \n");
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
            finally
            {
                this.Close();
            }
        }
Пример #57
0
        public static void Compress(string zipFilePath, string sourceDirPath, string password)
        {
            using (var zipFile = new ZipFileManager(SharedObjects.Encodings.ShiftJis))
            {
                if (password != null)
                {
                    zipFile.Password = password;
                }

                zipFile.AddDirectory(sourceDirPath);
                zipFile.Save(zipFilePath);
            }
        }
Пример #58
0
        public void Delete(string name)
        {
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(Path))
            {
                List <string> fullist = zip.EntryFileNames.ToList();
                if (name[name.Length - 1] == '/')
                {
                    name = name.Remove(name.Length - 1, 1) + "\\";
                }
                zip.RemoveEntry(name.Replace('\\', '/'));

                zip.Save();
            }
        }
Пример #59
0
        /// <summary>
        /// Writes the info back to the file
        /// </summary>
        /// <param name="fileName"></param>
        public void Update(string fileName)
        {
            archive = null;

            archive = ZipFile.Read(fileName);

            string data = json.ToString(); //converts info back to string

            archive.Comment = data;        //hmmmm

            archive.Save();

            archive = null;
        }
Пример #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);             
      }
    }