コード例 #1
0
ファイル: Form1.cs プロジェクト: FatihOz90/MSSQL-Backups-Tool
        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();
        }
コード例 #2
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);            
      }        
    }
コード例 #3
0
ファイル: Program.cs プロジェクト: huoxudong125/VideoSearch
        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);
            }
        }
コード例 #4
0
ファイル: Compression.cs プロジェクト: Capnode/Algoloop
 /// <summary>
 /// Return the entry file names contained in a zip file
 /// </summary>
 /// <param name="zipFileStream">Stream to the file</param>
 /// <returns>IEnumerable of entry file names</returns>
 public static IEnumerable <string> GetZipEntryFileNames(Stream zipFileStream)
 {
     using (var zip = ZipFile.Read(zipFileStream))
     {
         return(zip.EntryFileNames);
     }
 }
コード例 #5
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;
        }
コード例 #6
0
ファイル: Book.cs プロジェクト: karino2/wikipediaconv
        /// <summary>
        /// Create a TOC from the chapters and create the file
        /// </summary>
        /// <param name="filename"></param>
        public void Save(string filename)
        {
            using (ZipFile zippedBook = new ZipFile())
            {
                zippedBook.ForceNoCompression = true;
                ZipEntry mimetype = zippedBook.AddEntry("mimetype", "", "application/epub+zip");

                zippedBook.ForceNoCompression = false;

                zippedBook.AddEntry("container.xml", "META-INF", GetResource("EPubLib.Files.META_INF.container.xml"));
                zippedBook.AddEntry("content.opf", "OEBPS", GetContentOpf(), Encoding.UTF8);
                zippedBook.AddEntry("toc.ncx", "OEBPS", GetToc(), Encoding.UTF8);

                foreach (Chapter chapter in GetChapters())
                {
                    zippedBook.AddEntry("chapter" + chapter.Number.ToString("000") + ".xhtml", "OEBPS", chapter.Content, Encoding.UTF8);
                }
                foreach (FileItem image in GetImages())
                {
                    zippedBook.AddEntry(image.Name, "OEBPS/images", image.Data);
                }

                zippedBook.Save(filename);
            }
        }
コード例 #7
0
        private void PrepareScripts(string name, string url, string zipPassword)
        {
            _scriptsPath = Path.Combine(_downloadTo, name);

            string scriptsFileName = Path.ChangeExtension(name, "zip");
            string scriptsFilePath = Path.Combine(_downloadTo, scriptsFileName);

            (new FileInfo(scriptsFilePath)).Directory?.Create();

            File.Delete(scriptsFilePath);

            using (WebClient client = new WebClient())
            {
                client.DownloadFile(url, scriptsFilePath);
                _output.WriteLine($"Downloaded {scriptsFileName}.");
            }

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (ZipFile archive = new ZipFile(scriptsFilePath))
            {
                archive.Password = zipPassword;
                archive.ExtractAll(_scriptsPath, ExtractExistingFileAction.OverwriteSilently);
                _output.WriteLine($"Extracted {scriptsFileName} into {_scriptsPath}.");
            }
        }
        public static bool ExtractFileFromZip(TriggerReader reader)
        {
            string fileToSnatch = reader.ReadString();
            string zipFile      = reader.ReadString();

            try
            {
                using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile))
                {
                    foreach (ZipEntry entry in zip.Entries)
                    {
                        if (entry.FileName.Equals(fileToSnatch))
                        {
                            entry.Extract();
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
コード例 #9
0
        //public static byte[] Zip(string filename, byte[] bytes)
        //{

        //    var memOrigen = new MemoryStream(bytes);
        //    var memDestino = new MemoryStream();
        //    byte[] resultado = null;

        //    using (var fileZip = new ZipFile($"{filename}.zip"))
        //    {
        //        fileZip.AddEntry($"{filename}.xml", memOrigen);
        //        fileZip.Save(memDestino);
        //        resultado = memDestino.ToArray();
        //    }
        //    // Liberamos memoria RAM.
        //    memOrigen.Close();
        //    memDestino.Close();

        //    return resultado;
        //}

        /// <summary>
        /// Uns the zip.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="path">The path.</param>
        public static void UnZip(string fileName, string path)
        {
            using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(fileName))
            {
                zip.ExtractAll(path);
            }
        }
コード例 #10
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();
        }
コード例 #11
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();
        }
コード例 #12
0
ファイル: FileService.cs プロジェクト: bergziege/TmplGen
 /// <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);
     }
 }
コード例 #13
0
        public List <string> ProcessZipArchive(string archivePath, string pathToExtract)
        {
            try
            {
                List <string> exrtactedFiles = new List <string>();
                using (ZipFile zip = ZipFile.Read(archivePath))
                {
                    var renamedFolder = string.Empty;
                    var guid          = Guid.NewGuid().ToString().Substring(0, 6);

                    foreach (ZipEntry zipEntry in zip)
                    {
                        var zipFileName   = zipEntry.FileName;
                        var extractFolder = Path.Combine(pathToExtract, zipFileName);
                        int slashIndex    = zipFileName.IndexOf(@"/", StringComparison.CurrentCulture);

                        if (Directory.Exists(extractFolder) || File.Exists(extractFolder))
                        {
                            extractFolder = slashIndex != -1 ? zipFileName.Substring(0, slashIndex) : extractFolder;
                            renamedFolder = zipEntry.IsDirectory
                                ? string.Format($"{zipFileName.Replace(@"/", "")}_{guid}")
                                : string.Format($"{extractFolder}_{guid}");
                            pathToExtract = Path.Combine(pathToExtract, renamedFolder);
                            Directory.CreateDirectory(pathToExtract);
                            zipEntry.Extract(pathToExtract);
                        }
                        else
                        {
                            try
                            {
                                zipEntry.Extract(pathToExtract);
                            }
                            catch (Exception ex)
                            {
                                return(new List <string>()
                                {
                                    String.Concat($"Error in {pathToExtract}", ex.Message.ToString())
                                });
                            }
                        }

                        if (zipEntry.IsDirectory)
                        {
                            continue;
                        }

                        var fileNameWithFolders = string.Concat(@"/Archives/", renamedFolder, @"/", zipFileName);
                        exrtactedFiles.Add(fileNameWithFolders);
                    }
                }
                return(exrtactedFiles);
            }
            catch (Exception ex)
            {
                return(new List <string>()
                {
                    String.Concat("Error", ex.Message.ToString())
                });
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: Bajtix/updatescript
        static void Unzip(string command)
        {
            string[] cmd = command.Split(';');

            string from = cmd[0].Cmdify();
            string to   = cmd[1].Cmdify();

            Print("Unzipping " + from + " to " + to + "...");
            if (!File.Exists(from))
            {
                PrintLine("Failed. The source file does not exist.");
                breakOperation = true;
                return;
            }
            Directory.CreateDirectory(to);
            try {
                using (ZipFile zip1 = ZipFile.Read(from)) {
                    foreach (ZipEntry e in zip1)
                    {
                        e.Extract(to, ExtractExistingFileAction.OverwriteSilently);
                    }
                }
            } catch (IOException ie) {
                PrintLine("ionum " + ie.HResult);
                Print("An IO error occured.");
                breakOperation = true;
            }
            catch (Exception e) {
                PrintLine("An error occured: " + e.Message);
                breakOperation = true;
            }
            finally {
                PrintLine("Unzipped.");
            }
        }
コード例 #15
0
 private void button3_Click(object sender, RoutedEventArgs e)
 {
     Directory.SetCurrentDirectory("C:/tmp/soundpcker");
     using (ZipFile zip = new ZipFile())
     {
         // add this map file into the "images" directory in the zip archive
         zip.AddFile("pack.mcmeta");
         // add the report into a different directory in the archive
         zip.AddItem("assets");
         zip.AddFile("lcrm");
         zip.Save("CustomSoundInjector_ResourcePack.zip");
     }
         SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.DefaultExt = ".zip";
     saveFileDialog.Filter = "Minecraft ResourcePack (with Bytecode)|*.zip";
     if (saveFileDialog.ShowDialog() == true)
     {
         exportpath = saveFileDialog.FileName;
     }
     else
     {
         MessageBox.Show("Operation Cancelled.", "Cancelled", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     string originExport = "C:/tmp/soundpcker/CustomSoundInjector_ResourcePack.zip";
     File.Copy(originExport, exportpath, true);
     MessageBox.Show("Saved.", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
 }
コード例 #16
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));
                }
            }
        }
コード例 #17
0
ファイル: ArchiveService.cs プロジェクト: evkap/DVS
		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();
				}
			}
		}
コード例 #18
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"));
                }
            }
        }
コード例 #19
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);
     }
 }
コード例 #20
0
ファイル: TexturePack.cs プロジェクト: fcraft-based/GemsCraft
 public TexturePack(string file)
 {
     IsTerrainPng = Path.GetExtension(file) == ".png";
     try
     {
         if (IsTerrainPng)
         {
             Terrain = Image.FromFile(file);
         }
         else
         {
             _baseZip = file;
             using (ZipFile zip = ZipFile.Read(file))
             {
                 if (File.Exists(TerrainFile))
                 {
                     File.Delete(TerrainFile);
                 }
                 ZipEntry e = zip[TerrainFile];
                 e.Extract(Server.BaseDirectory);
                 Terrain = Image.FromFile(TerrainFile);
             }
         }
     }
     catch (FileNotFoundException)
     {
         Logger.Log(LogType.Error, "Texture pack not found!");
     }
     catch (Exception ex)
     {
         Logger.Log(LogType.Error, "Unable to load texture pack!");
         Logger.Log(LogType.Error, ex.ToString());
     }
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: FloodProject/flood
        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;
        }
コード例 #22
0
ファイル: TexturePack.cs プロジェクト: fcraft-based/GemsCraft
        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);
            }
        }
コード例 #23
0
ファイル: ZipHelper.cs プロジェクト: yetanothervan/conspector
        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"));
        }
コード例 #24
0
 public static void ExtractZip(string zipFile, string destino)
 {
     if (File.Exists(zipFile))
     {
         //recebe a localização do arquivo zip
         using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFile))
         {
             //verifica se o destino existe
             if (Directory.Exists(destino))
             {
                 try
                 {
                     //extrai o arquivo zip para o destino
                     zip.ExtractAll(destino);
                 }
                 catch (Exception ex)
                 {
                     throw new Exception("Falha na extração do zip " + zipFile, ex);
                 }
             }
             else
             {
                 //lança uma exceção se o destino não existe
                 throw new DirectoryNotFoundException("O arquivo destino não foi localizado");
             }
         }
     }
     else
     {
         //lança uma exceção se a origem não existe
         throw new FileNotFoundException("O Arquivo Zip não foi localizado");
     }
 }
コード例 #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
ファイル: ZipHelper.cs プロジェクト: initialsam/Yame.Tools
        /// <summary>
        /// 解壓縮後刪除Zip檔
        /// </summary>
        /// <param name="fullPathDto"></param>
        /// <param name="zipPassword"></param>
        /// <returns></returns>
        public static bool UnZipAndDelete(FullPathDto fullPathDto, string zipPassword)
        {
            if (File.Exists(fullPathDto.LocalZipFullPath))
            {
                try
                {
                    var options = new ReadOptions {
                        StatusMessageWriter = System.Console.Out
                    };
                    using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(fullPathDto.LocalZipFullPath, options))
                    {
                        zip.Password = zipPassword;                                                           // 解壓密碼
                        zip.ExtractAll(fullPathDto.LocalFolder, ExtractExistingFileAction.OverwriteSilently); // 解壓全部
                    }
                    File.Delete(fullPathDto.LocalZipFullPath);
                    if (File.Exists(fullPathDto.LocalXmlFullPath))
                    {
                        Console.WriteLine($"解ZIP 成功 XML: {fullPathDto.LocalXmlFullPath}");
                        return(true);
                    }

                    return(false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"解ZIP {fullPathDto.LocalZipFullPath} 發生錯誤 {ex}");
                }
            }

            return(false);
        }
コード例 #27
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);             
      }
    }
コード例 #28
0
 public void Comprimir()
 {
     using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) {
         zip.AddFile("transacoes.csv");
         zip.Save("banco_de_dados.zip");
     }
 }
コード例 #29
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();
            }
        }
コード例 #30
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);
 }
コード例 #31
0
ファイル: Updater.cs プロジェクト: Frostbrood/StealthClient
        private void bgWorker_Finish(object sender, RunWorkerCompletedEventArgs e)
        {
            dlElapsedTimer.Stop();
            try
            {
                if (File.Exists(zipTarget))
                {
                    using (ZipFile zip = new ZipFile(zipTarget))
                    {
                        zip.ExtractAll(Directory.GetCurrentDirectory(), ExtractExistingFileAction.OverwriteSilently);
                        zip.Dispose();
                    }

                    File.Delete(zipTarget);
                    Process start = new Process();
                    start.StartInfo.FileName = exeTarget;
                    start.StartInfo.Arguments = "ProcessStart.cs";
                    start.Start();
                    Application.Exit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error with the updater. Check your connection and try running as an administrator.\r\n\r\n" + ex.Message);
                Application.Exit();
            }
        }
コード例 #32
0
ファイル: Entity.cs プロジェクト: Svetuf/FileManager
        public List <string> GetAllFiles()
        {
            using (Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(path))
            {
                zip.AlternateEncoding = Encoding.Default;
                List <string> fulList   = zip.EntryFileNames.ToList();
                List <string> shortList = new List <string>();
                int           i         = 0;
                foreach (string elem in fulList)
                {
                    i = elem.IndexOf("/");
                    if (i != -1)
                    {
                        shortList.Add(elem.Substring(0, i) + "/");
                    }
                    else
                    {
                        shortList.Add(elem);
                    }
                }
                //List<string> gi = shortList.Distinct().ToList();

                return(shortList.Distinct().ToList());
            }
        }
コード例 #33
0
ファイル: ArchiveService.cs プロジェクト: evkap/DVS
		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;
		}
コード例 #34
0
ファイル: DataAction.cs プロジェクト: dobriyeeh/simpkup
        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);
            }
        }
コード例 #35
0
        private bool OpenZip(String path, out string outpath)
        {
            //ZipFileを作成する
            using (Ionic.Zip.ZipFile zip = ZipFile.Read(path, new ReadOptions()
            {
                Encoding = Encoding.GetEncoding("shift_jis")
            }))
            {
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;

                zip.ExtractExistingFile = Ionic.Zip.ExtractExistingFileAction.OverwriteSilently;
                //エラーが出てもスキップする。デフォルトはThrow。
                zip.ZipErrorAction = Ionic.Zip.ZipErrorAction.Skip;

                zip.Password   = "******";
                zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;

                // Tempフォルダーに書き出し隔離
                string tempFolder = Path.GetTempPath() + Path.GetRandomFileName();
                Directory.CreateDirectory(tempFolder);

                //フォルダを追加する
                zip.ExtractAll(tempFolder);

                outpath = tempFolder;
            }

            return(true);
        }
コード例 #36
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.");
        }
コード例 #37
0
        public void Export(Repository repository, string baseFolder, string[] folders, string[] docs, Stream outputStream)
        {
            ZipFile zipFile = new ZipFile();
            var basePrefix = StorageNamesEncoder.EncodeContainerName(repository.Name) + "/" + MediaBlobHelper.MediaDirectoryName + "/";
            if (!string.IsNullOrEmpty(baseFolder))
            {
                var baseMediaFolder = ServiceFactory.MediaFolderManager.Get(repository, baseFolder);
                basePrefix = baseMediaFolder.GetMediaFolderItemPath(null) + "/";
            }

            var blobClient = CloudStorageAccountHelper.GetStorageAccount().CreateCloudBlobClient();

            //add file
            if (docs != null)
            {
                foreach (var doc in docs)
                {
                    var blob = blobClient.GetBlockBlobReference(basePrefix + StorageNamesEncoder.EncodeBlobName(doc));

                    var bytes = blob.DownloadByteArray();
                    zipFile.AddEntry(doc, bytes);
                }
            }
            //add folders
            if (folders != null)
            {
                foreach (var folder in folders)
                {
                    var folderName = folder.Split('~').LastOrDefault();
                    zipFolder(blobClient, basePrefix, folderName, "", ref zipFile);
                }
            }
            zipFile.Save(outputStream);
        }
コード例 #38
0
ファイル: DotNetZip.cs プロジェクト: NetUtil/Util
 /// <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 ) );
     }
 }
コード例 #39
0
ファイル: ZipHelper.cs プロジェクト: kiwipiet/CleanProject
        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();
            }
        }
コード例 #40
0
        /// <summary>
        /// We read the file info
        /// </summary>
        /// <param name="fileName"></param>
        public void Init(string fileName)
        {
            archive = null;

            archive = ZipFile.Read(fileName);

            string data = archive.Comment;

            archive = null;

            try
            {
                if (data != null && data != String.Empty)
                {
                    json = JObject.Parse(data);
                }
                else
                {
                    json = JObject.Parse(CreateDefaultInfo());
                }

                comicbookinfo = (JObject)json["ComicBookInfo/1.0"];
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
コード例 #41
0
        /// <summary>
        /// Extracts the contents of a zip file
        /// </summary>
        /// <param name="ZipFileName">Name of the zip file</param>
        /// <param name="BaseDirectory">Output directory</param>
        /// <returns>List of files written</returns>
        public static IEnumerable <string> UnzipFiles(string ZipFileName, string BaseDirectory)
        {
            // manually extract the files. There was a problem with the Ionic.Zip library that required this on non-PC at one point,
            // but that problem is now fixed. Leaving this code as is as we need to return the list of created files and fix up their permissions anyway.
            using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(ZipFileName))
            {
                List <string> OutputFileNames = new List <string>();
                foreach (Ionic.Zip.ZipEntry Entry in Zip.Entries)
                {
                    // support-v4 and support-v13 has the jar file named with "internal_impl-XX.X.X.jar"
                    // this causes error "Found 2 versions of internal_impl-XX.X.X.jar"
                    // following codes adds "support-v4-..." to the output jar file name to avoid the collision
                    string OutputFileName = Path.Combine(BaseDirectory, Entry.FileName);
                    if (Entry.FileName.Contains("internal_impl"))
                    {
                        string _ZipName          = Path.GetFileNameWithoutExtension(ZipFileName);
                        string NewOutputFileName = Path.Combine(Path.GetDirectoryName(OutputFileName),
                                                                _ZipName + '-' + Path.GetFileNameWithoutExtension(OutputFileName) + '.' + Path.GetExtension(OutputFileName));
                        Log.TraceInformation("Changed FileName {0} => {1}", Entry.FileName, NewOutputFileName);
                        OutputFileName = NewOutputFileName;
                    }

                    Directory.CreateDirectory(Path.GetDirectoryName(OutputFileName));
                    if (!Entry.IsDirectory)
                    {
                        using (FileStream OutputStream = new FileStream(OutputFileName, FileMode.Create, FileAccess.Write))
                        {
                            Entry.Extract(OutputStream);
                        }
                        OutputFileNames.Add(OutputFileName);
                    }
                }
                return(OutputFileNames);
            }
        }
コード例 #42
0
        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);
        }
コード例 #43
0
ファイル: Compression.cs プロジェクト: Capnode/Algoloop
        } // End UnZip

        /// <summary>
        /// Unzip a stream that represents a zip file and return the first entry as a stream
        /// </summary>
        public static Stream UnzipStream(Stream zipstream, out ZipFile zipFile, string entryName = null)
        {
            zipFile = ZipFile.Read(zipstream);

            try
            {
                Ionic.Zip.ZipEntry entry;
                if (string.IsNullOrEmpty(entryName))
                {
                    //Read the file entry into buffer:
                    entry = zipFile.Entries.FirstOrDefault();
                }
                else
                {
                    // Attempt to find our specific entry
                    if (!zipFile.ContainsEntry(entryName))
                    {
                        return(null);
                    }
                    entry = zipFile[entryName];
                }

                if (entry != null)
                {
                    return(entry.OpenReader());
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
            }

            return(null);
        } // End UnZip
コード例 #44
0
ファイル: PackageManager.cs プロジェクト: wurdum/deployer
 public void FolderToZip(string sourceDir, string path)
 {
     using (var surveyBackup = new ZipFile()) {
         surveyBackup.AddDirectory(sourceDir);
         surveyBackup.Save(path);
     }
 }
コード例 #45
0
ファイル: ZipUtil.cs プロジェクト: kevins1022/Altman
 /// <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;
     }
 }
コード例 #46
0
        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;
        }
コード例 #47
0
 private void button9_Click(object sender, EventArgs e)
 {
     if (File.Exists(Application.StartupPath + @"\Toolbox\XMB Modder\PS3_XMB_Modder.exe"))
     {
         this.WindowState = FormWindowState.Minimized;
         System.Diagnostics.Process.Start(Application.StartupPath + @"\Toolbox\XMB Modder\PS3_XMB_Modder.exe");
     }
     else
     {
         DialogResult result = MessageBox.Show("This File Needs To Be Downloaded First", "Continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
         if (DialogResult.Yes == result && System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
         {
             DownloadFile("http://www.xxxthedartkprogramerxxx.net/Download/XMB Modder.zip", Application.StartupPath + @"\Toolbox\XMB Modder.zip");
             this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracting", "Extracting XMB Modder Please Wait", ToolTipIcon.Info);
             Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Application.StartupPath + @"\Toolbox\XMB Modder.zip");
             zip.ExtractAll(Application.StartupPath + @"\Toolbox\");
             this.notifyIcon1.ShowBalloonTip(0x7d0, "Extracted", "Opening File", ToolTipIcon.Info);
             this.WindowState = FormWindowState.Minimized;
             System.Diagnostics.Process.Start(Application.StartupPath + @"\Toolbox\XMB Modder\PS3_XMB_Modder.exe");
             File.Delete(Application.StartupPath + @"\Toolbox\XMB Modder.zip");
         }
         else if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false)
         {
             MessageBox.Show("You Need An Internet Connection For This");
         }
     }
 }
コード例 #48
0
 /// <summary>
 /// Builds the DLL with the latest class files to ensure it's up to date.
 /// Adds the 51Degrees and Sitecore interface DLL to the package.
 /// </summary>
 /// <param name="package"></param>
 /// <param name="projectFile"></param>
 private static void BuildDlls(ZipFile package, FileInfo projectFile)
 {
     var outputPath = Path.Combine(
     Path.GetTempPath(),
     "Sitecore.SharedSource.MobileDeviceDetector");
       Directory.CreateDirectory(outputPath);
       var msBuildPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "msbuild.exe");
       var startInfo = new ProcessStartInfo(msBuildPath)
       {
     Arguments = string.Format(
       @"""{0}"" /t:rebuild /p:Configuration=Release /p:OutputPath=""{1}""",
       projectFile.FullName,
       outputPath),
     WorkingDirectory = Path.GetDirectoryName(msBuildPath),
     RedirectStandardOutput = true,
     RedirectStandardError = true,
     UseShellExecute = false
       };
       Console.WriteLine("> msbuild " + startInfo.Arguments);
       var process = Process.Start(startInfo);
       Console.Write(process.StandardOutput.ReadToEnd());
       process.WaitForExit();
       AddDll(package,
     outputPath,
     "Sitecore.SharedSource.MobileDeviceDetector.dll");
       AddDll(package,
     outputPath,
     "FiftyOne.Foundation.dll");
       Directory.Delete(outputPath, true);
 }
コード例 #49
0
ファイル: Program.cs プロジェクト: davinx/MediaPortal-2
    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
    }
コード例 #50
0
        /// <summary>
        /// Opens a file in preparation for writing a series of image entries
        /// should load the manifest so we can add / remove entries from it
        /// </summary>
        /// <returns></returns>
        public bool OpenSceneFile(string scenefilename) 
        {
            try
            {
                mZip = ZipFile.Read(scenefilename);
                //open the manifest file                
                string xmlname = "manifest.xml";
                ZipEntry manifestentry = mZip[xmlname];
                //get memory stream
                MemoryStream manistream = new MemoryStream();
                //extract the stream
                manifestentry.Extract(manistream);
                //read from stream
                manistream.Seek(0, SeekOrigin.Begin); // rewind the stream for reading
                //create a new XMLHelper to load the stream into
                mManifest = new XmlHelper();
                //load the stream
                mManifest.LoadFromStream(manistream, "manifest");

                return true;
            }
            catch (Exception ex) 
            {
                DebugLogger.Instance().LogError(ex);
            }
            return false;
        }
コード例 #51
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);       
      }
    }
コード例 #52
0
ファイル: Packager.cs プロジェクト: JatinR/quest
        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;
        }
コード例 #53
0
ファイル: ResourceLoader.cs プロジェクト: makesj/vienna
 protected ResourceLoader(string path, int cacheMb)
 {
     Path = path;
     Cache = new ResourceCache(cacheMb);
     Extractor = new ZipFile(path);
     BuildIndex();
 }
コード例 #54
0
ファイル: AppHelper.cs プロジェクト: koufengwei/Brake
 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;
 }
コード例 #55
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);
					}
				}
			}
		}
コード例 #56
0
ファイル: ZipComic.cs プロジェクト: adamhathcock/comictoolx
 public override void Open(string file)
 {
     zf = ZipFile.Read (file);
     Pages = zf.Where (entry => (!entry.IsDirectory && IsValidImage (entry.FileName)))
         .OrderBy (e => e.FileName)
         .Select (e => new ZipPage (e)).ToList<Page> ();
 }
コード例 #57
0
        protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
        {
            if (!File.Exists(fileName))
            {
                Assert.True(false, "File '" + fileName + "' doesn't exist.");
            }

            byte[] encodedBuf = encoding.GetBytes(contents);

            using (var zip = new Ionic.Zip.ZipFile(fileName))
            {
                Assert.Equal(1, zip.Count);
                Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize);

                byte[] buf = new byte[zip[0].UncompressedSize];
                using (var fs = zip[0].OpenReader())
                {
                    fs.Read(buf, 0, buf.Length);
                }

                for (int i = 0; i < buf.Length; ++i)
                {
                    Assert.Equal(encodedBuf[i], buf[i]);
                }
            }
        }
コード例 #58
0
ファイル: TextureLump.cs プロジェクト: kungfooman/uQuake3
        private void LoadTGATextures(ZipFile pk3)
        {
            foreach (Texture tex in Textures)
            {
                // The size of the new Texture2D object doesn't matter. It will be replaced (including its size) with the data from the texture that's getting pulled from the pk3 file.
                if (pk3.ContainsEntry(tex.Name + ".tga"))
                {
                    Texture2D readyTex = new Texture2D(4, 4);
                    var entry = pk3 [tex.Name + ".tga"];
                    using (var stream = entry.OpenReader())
                    {
                        var ms = new MemoryStream();
                        entry.Extract(ms);
                        readyTex = TGALoader.LoadTGA(ms);
                    }

                    readyTex.name = tex.Name;
                    readyTex.filterMode = FilterMode.Trilinear;
                    readyTex.Compress(true);

                    if (readyTextures.ContainsKey(tex.Name))
                    {
                        Debug.Log("Updating texture with name " + tex.Name + ".tga");
                        readyTextures [tex.Name] = readyTex;
                    } else
                        readyTextures.Add(tex.Name, readyTex);
                }
            }
        }
コード例 #59
0
    /// <summary>
    /// Extracts the contents of a zip file
    /// </summary>
    /// <param name="ZipFileName">Name of the zip file</param>
    /// <param name="BaseDirectory">Output directory</param>
    /// <returns>List of files written</returns>
    public static IEnumerable <string> InternalUnzipFiles(string ZipFileName, string BaseDirectory)
    {
        // manually extract the files. There was a problem with the Ionic.Zip library that required this on non-PC at one point,
        // but that problem is now fixed. Leaving this code as is as we need to return the list of created files and fix up their permissions anyway.
        using (Ionic.Zip.ZipFile Zip = new Ionic.Zip.ZipFile(ZipFileName))
        {
            List <string> OutputFileNames = new List <string>();
            foreach (Ionic.Zip.ZipEntry Entry in Zip.Entries)
            {
                string OutputFileName = Path.Combine(BaseDirectory, Entry.FileName);
                Directory.CreateDirectory(Path.GetDirectoryName(OutputFileName));

                //Check to make sure that we do not output to file stream if the entry is a directory.
                if (!Entry.IsDirectory)
                {
                    using (FileStream OutputStream = new FileStream(OutputFileName, FileMode.Create, FileAccess.Write))
                    {
                        Entry.Extract(OutputStream);
                    }
                }

                if (UnrealBuildTool.Utils.IsRunningOnMono && CommandUtils.IsProbablyAMacOrIOSExe(OutputFileName))
                {
                    FixUnixFilePermissions(OutputFileName);
                }
                OutputFileNames.Add(OutputFileName);
            }
            return(OutputFileNames);
        }
    }
コード例 #60
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);
        }