CreateEntry() public method

public CreateEntry ( string entryName ) : System.IO.Compression.ZipArchiveEntry
entryName string
return System.IO.Compression.ZipArchiveEntry
        public async Task <MemoryStream> GenerateZip(string report, string log)
        {
            using var ms      = new MemoryStream();
            using var archive =
                      new System.IO.Compression.ZipArchive(ms, ZipArchiveMode.Create, true);
            byte[] reportBytes = Encoding.ASCII.GetBytes(report);
            byte[] logBytes    = Encoding.ASCII.GetBytes(log);

            var zipEntry = archive.CreateEntry("Report.trx",
                                               CompressionLevel.Fastest);

            using (var zipStream = zipEntry.Open())
            {
                await zipStream.WriteAsync(reportBytes, 0, reportBytes.Length).ConfigureAwait(false);
            }

            var zipEntry2 = archive.CreateEntry("log.txt",
                                                CompressionLevel.Fastest);

            using (var zipStream = zipEntry2.Open())
            {
                await zipStream.WriteAsync(logBytes, 0, logBytes.Length).ConfigureAwait(false);
            }
            return(ms);
        }
コード例 #2
0
        private static Stream CreateTestPackageStream()
        {
            var packageStream = new MemoryStream();
            using (var packageArchive = new ZipArchive(packageStream, ZipArchiveMode.Create, true))
            {
                var nuspecEntry = packageArchive.CreateEntry("TestPackage.nuspec", CompressionLevel.Fastest);
                using (var streamWriter = new StreamWriter(nuspecEntry.Open()))
                {
                    streamWriter.WriteLine(@"<?xml version=""1.0""?>
                    <package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
                      <metadata>
                        <id>TestPackage</id>
                        <version>0.0.0.1</version>
                        <title>Package A</title>
                        <authors>ownera, ownerb</authors>
                        <owners>ownera, ownerb</owners>
                        <requireLicenseAcceptance>false</requireLicenseAcceptance>
                        <description>package A description.</description>
                        <language>en-US</language>
                        <projectUrl>http://www.nuget.org/</projectUrl>
                        <iconUrl>http://www.nuget.org/</iconUrl>
                        <licenseUrl>http://www.nuget.org/</licenseUrl>
                        <dependencies />
                      </metadata>
                    </package>");
                }

                packageArchive.CreateEntry("content\\HelloWorld.cs", CompressionLevel.Fastest);
            }

            packageStream.Position = 0;

            return packageStream;
        }
コード例 #3
0
        private void ZipPackage(PassGeneratorRequest request)
        {
            using (MemoryStream zipToOpen = new MemoryStream())
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update, true))
                {
					foreach (KeyValuePair<PassbookImage, byte[]> image in request.Images)
					{	
						ZipArchiveEntry imageEntry = archive.CreateEntry(image.Key.ToFilename());

						using (BinaryWriter writer = new BinaryWriter(imageEntry.Open()))
						{
							writer.Write(image.Value);
							writer.Flush();
						}
					}

					foreach (KeyValuePair<string, byte[]> localization in localizationFiles)
					{
						ZipArchiveEntry localizationEntry = archive.CreateEntry(string.Format ("{0}.lproj/pass.strings", localization.Key.ToLower()));

						using (BinaryWriter writer = new BinaryWriter(localizationEntry.Open()))
						{
							writer.Write(localization.Value);
							writer.Flush();
						}
					}

                    ZipArchiveEntry PassJSONEntry = archive.CreateEntry(@"pass.json");
                    using (BinaryWriter writer = new BinaryWriter(PassJSONEntry.Open()))
                    {
                        writer.Write(passFile);
                        writer.Flush();
                    }

                    ZipArchiveEntry ManifestJSONEntry = archive.CreateEntry(@"manifest.json");
                    using (BinaryWriter writer = new BinaryWriter(ManifestJSONEntry.Open()))
                    {
                        writer.Write(manifestFile);
                        writer.Flush();
                    }

                    ZipArchiveEntry SignatureEntry = archive.CreateEntry(@"signature");
                    using (BinaryWriter writer = new BinaryWriter(SignatureEntry.Open()))
                    {
                        writer.Write(signatureFile);
                        writer.Flush();
                    }
                }

                pkPassFile = zipToOpen.ToArray();
                zipToOpen.Flush();
            }
        }
コード例 #4
0
ファイル: File.cs プロジェクト: JBonsink/BaxterLicence
        public static byte[] Zip(List<Tuple<string, byte[]>> files)
        {
            using (var compressedFileStream = new MemoryStream())
            {
                //Create an archive and store the stream in memory.
                using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                {
                    foreach (var file in files)
                    {
                        //Create a zip entry for each attachment
                        var zipEntry = zipArchive.CreateEntry(file.Item1);

                        //Get the stream of the attachment
                        using (var originalFileStream = new MemoryStream(file.Item2))
                        {
                            using (var zipEntryStream = zipEntry.Open())
                            {
                                //Copy the attachment stream to the zip entry stream
                                originalFileStream.CopyTo(zipEntryStream);
                            }
                        }
                    }
                }
                return compressedFileStream.ToArray();
            }
        }
コード例 #5
0
ファイル: ZipService.cs プロジェクト: Coft/Coft.ImageResizer
        public void ParseZip(FileStream zipToOpen, FileStream zipToWrite, Predicate<string> fileNameFilter, Action<Stream, Stream> parseAction, Action<int> processingPercentage)
        {
            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read),
                                newArchive = new ZipArchive(zipToWrite, ZipArchiveMode.Create))
            {
                int entriesDone = 0;
                int entriesCount = archive.Entries.Count;

                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    processingPercentage(100 * entriesDone++ / entriesCount);

                    if (fileNameFilter(entry.Name))
                    {
                        ZipArchiveEntry newEntry = newArchive.CreateEntry(entry.FullName);

                        using (Stream stream = entry.Open(),
                            newStream = newEntry.Open())
                        {
                            parseAction(stream, newStream);
                        }
                    }
                }
            }
        }
コード例 #6
0
ファイル: CreateZipArchive.cs プロジェクト: csf-dev/ZPT-Sharp
 public override bool Execute()
 {
     // Originally taken from https://peteris.rocks/blog/creating-release-zip-archive-with-msbuild/
       // Then modified not to be inline anymore
       try
       {
     using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
     using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
     {
       foreach (ITaskItem fileItem in Files)
       {
     string filename = fileItem.ItemSpec;
     using (Stream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
     using (Stream fileStreamInZip = archive.CreateEntry(new FileInfo(filename).Name).Open())
       fileStream.CopyTo(fileStreamInZip);
       }
     }
     return true;
       }
       catch (Exception ex)
       {
     Log.LogErrorFromException(ex);
     return false;
       }
 }
コード例 #7
0
        public FileResult ExprortFromDb()
        {
            try
            {
                if (IocHelper.CurrentToggle != "db")
                {
                    throw new Exception("Экспорт возможен только из БД");
                }
                var helper = new IocHelper();

                using (var memoryStream = new MemoryStream())
                {
                    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        var demoFile = archive.CreateEntry("db_export.xml", CompressionLevel.Optimal);

                        using (var entryStream = demoFile.Open())
                        using (var streamWriter = new StreamWriter(entryStream))
                        {
                            streamWriter.Write(helper.ArticleService.ExportFromDb());
                        }
                    }
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    return File(memoryStream.ToArray(), "application/zip", "db_export.zip");
                }
            }
            catch (Exception e)
            {
                throw new HttpException(500, e.Message);
            }
        }
コード例 #8
0
ファイル: FileZipper.cs プロジェクト: dibiancoj/ToracLibrary
        /// <summary>
        /// Zip's up a list of files where you only have the byte array. So everything is in memory, and you want to zip it up and send it for download or do something else with a byte array
        /// </summary>
        /// <param name="FilesToZip">Files To Zip Up. Key is the file name and the value is the byte array which contains the file</param>
        /// <returns>The Zipped up files in a byte array</returns>
        public static byte[] ZipByteArray(IDictionary<string, byte[]> FilesToZip)
        {
            //create the memory stream which the zip will be created with
            using (var MemoryStreamToCreateZipWith = new MemoryStream())
            {
                //declare the working zip archive
                using (var WorkingZipArchive = new ZipArchive(MemoryStreamToCreateZipWith, ZipArchiveMode.Update, false))
                {
                    //loop through each of the files and add it to the working zip
                    foreach (var FileToZipUp in FilesToZip)
                    {
                        //Create a zip entry for each attachment
                        var ZipEntry = WorkingZipArchive.CreateEntry(FileToZipUp.Key);

                        //Get the stream of the attachment
                        using (var FileToZipUpInMemoryStream = new MemoryStream(FileToZipUp.Value))
                        {
                            //grab the memory stream from the zip entry
                            using (var ZipEntryStream = ZipEntry.Open())
                            {
                                //Copy the attachment stream to the zip entry stream
                                FileToZipUpInMemoryStream.CopyTo(ZipEntryStream);
                            }
                        }
                    }
                }

                //all done, so go return the byte array which contains the zipped up file bytes
                return MemoryStreamToCreateZipWith.ToArray();
            }
        }
コード例 #9
0
ファイル: Shims.cs プロジェクト: AparnaSGhenge/Hello_World
    private void Zip(AbsolutePath target, IEnumerable <string> paths)
    {
        var  targetPath = target.ToString();
        bool finished = false, atLeastOneFileAdded = false;

        try
        {
            using (var targetStream = File.Create(targetPath))
                using (var archive = new System.IO.Compression.ZipArchive(targetStream, ZipArchiveMode.Create))
                {
                    void AddFile(string path, string relativePath)
                    {
                        var e = archive.CreateEntry(relativePath.Replace("\\", "/"), CompressionLevel.Optimal);

                        using (var entryStream = e.Open())
                            using (var fileStream = File.OpenRead(path))
                                fileStream.CopyTo(entryStream);
                        atLeastOneFileAdded = true;
                    }

                    foreach (var path in paths)
                    {
                        if (Directory.Exists(path))
                        {
                            var dirInfo  = new DirectoryInfo(path);
                            var rootPath = Path.GetDirectoryName(dirInfo.FullName);
                            foreach (var fsEntry in dirInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                            {
                                if (fsEntry is FileInfo)
                                {
                                    var relPath = Path.GetRelativePath(rootPath, fsEntry.FullName);
                                    AddFile(fsEntry.FullName, relPath);
                                }
                            }
                        }
                        else if (File.Exists(path))
                        {
                            var name = Path.GetFileName(path);
                            AddFile(path, name);
                        }
                    }
                }

            finished = true;
        }
        finally
        {
            try
            {
                if (!finished || !atLeastOneFileAdded)
                {
                    File.Delete(targetPath);
                }
            }
            catch
            {
                //Ignore
            }
        }
    }
コード例 #10
0
ファイル: MemoryZip.cs プロジェクト: asipe/area51
        private void CompressUsingMemory()
        {
            var item = GetNextItem();
              while (item != null) {
            using (var strm = new MemoryStream()) {
              using (var archive = new ZipArchive(strm, ZipArchiveMode.Create, true)) {
            var cfg = new Config(item.Source) {ScanType = ScanType.FilesOnly};
            cfg.OnFile += (o, a) => {
              var entryPath = a.Path.Replace(item.Source + "\\", "");
              var entry = archive.CreateEntry(entryPath, CompressionLevel.Fastest);
              using (var entryStream = entry.Open()) {
                using (var fileStream = File.OpenRead(a.Path)) {
                  fileStream.CopyTo(entryStream);
                  fileStream.Close();
                }
                entryStream.Flush();
                entryStream.Close();
              }
            };
            Snarfzer.NewScanner().Start(cfg);
              }

              strm.Position = 0;
              using (var outstream = File.OpenWrite(item.Dest))
            strm.CopyTo(outstream);
            }
            item = GetNextItem();
              }
        }
コード例 #11
0
ファイル: ZipFileMock.cs プロジェクト: LazyTarget/Lux
        public static ZipFileMock Archive(string sourceDirectoryName, string destinationArchiveFileName, params FileMock[] files)
        {
            var bytes = new byte[0];
            using (var stream = new MemoryStream())
            {
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
                {
                    foreach (var file in files)
                    {
                        var relativePath = PathHelper.Subtract(file.Path, sourceDirectoryName);
                        var entry = archive.CreateEntry(relativePath);

                        using (var entryStream = entry.Open())
                        {
                            entryStream.Write(file.Bytes, 0, file.Bytes.Length);
                            entryStream.Flush();
                        }
                    }
                }

                // Fix for "invalid zip archive"
                using ( var fileStream = new MemoryStream() )
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(fileStream);
                    bytes = fileStream.ToArray();
                }
            }

            var zipFile = new ZipFileMock(destinationArchiveFileName, bytes, files);
            return zipFile;
        }
コード例 #12
0
        public static void Compres(string path, IFormFile file, FType fType)
        {
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);

            using (var ms = new MemoryStream())
            {
                using (var archive =
                           new System.IO.Compression.ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    MemoryStream memoryStream = new MemoryStream();
                    file.OpenReadStream().CopyTo(memoryStream);
                    var    strearFile = file.OpenReadStream();
                    byte[] fileByte   = memoryStream.ToArray();

                    var zipEntry = archive.CreateEntry(file.FileName,
                                                       CompressionLevel.Optimal);
                    using (var zipStream = zipEntry.Open())
                    {
                        zipStream.Write(fileByte, 0, fileByte.Length);
                        zipStream.Close();
                        fs.Write(ms.ToArray());
                        fs.Close();
                    }

                    //var zipEntry2 = archive.CreateEntry("image2.png",
                    //    CompressionLevel.Fastest);
                    //using (var zipStream = zipEntry2.Open())
                    //{
                    //    zipStream.Write(bytes2, 0, bytes2.Length);
                    //}
                }
            }
        }
コード例 #13
0
        private static string AddToArchive(string entryName, Stream inputStream, ZipArchive zipArchive, string hashName)
        {
            var entry = zipArchive.CreateEntry(entryName);

            HashAlgorithm hashAlgorithm = null;
            BinaryWriter zipEntryWriter = null;
            try
            {
                hashAlgorithm = HashAlgorithm.Create(hashName);
                zipEntryWriter = new BinaryWriter(entry.Open());

                var readBuffer = new byte[StreamReadBufferSize];
                int bytesRead;
                while ((bytesRead = inputStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    zipEntryWriter.Write(readBuffer, 0, bytesRead);
                    hashAlgorithm.TransformBlock(readBuffer, 0, bytesRead, readBuffer, 0);
                }
                hashAlgorithm.TransformFinalBlock(readBuffer, 0, 0);

                var hashHexStringBuilder = new StringBuilder();
                foreach (byte hashByte in hashAlgorithm.Hash)
                {
                    hashHexStringBuilder.Append(hashByte.ToString("x2"));
                }

                return hashHexStringBuilder.ToString();
            }
            finally
            {
                hashAlgorithm.SafeDispose();
                zipEntryWriter.SafeDispose();
            }
        }
コード例 #14
0
 public void GenerateZip(Models.WordList wordList, Stream outputStream)
 {
     using (ZipArchive zip = new ZipArchive(outputStream, ZipArchiveMode.Create, true))
     {
         ZipArchiveEntry wordsEntry = zip.CreateEntry(ZipWordListEntryName);
         GenerateXml(wordList, wordsEntry.Open());
     }
 }
コード例 #15
0
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
            var selected = new List<object>(TileList.SelectedItems);

            var picker = new FileSavePicker();
            picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
            var file = await picker.PickSaveFileAsync();
            if (file != null) {
                CachedFileManager.DeferUpdates(file);

                await FileIO.WriteTextAsync(file, "");
                
                using (var stream = await file.OpenStreamForWriteAsync())
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {

                    while (zip.Entries.Count > 0) {
                        zip.Entries[0].Delete();
                    }

                    using (var metaStream = zip.CreateEntry("tiles.json").Open())
                    using (var writer = new StreamWriter(metaStream)) {
                        var array = new JsonArray();

                        selected.ForEachWithIndex<SecondaryTile>((item, index) => {
                            var objet = new JsonObject();
                            objet.Add("Name", item.DisplayName);
                            objet.Add("Arguments", item.Arguments);
                            objet.Add("TileId", item.TileId);
                            objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
                            objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
                            objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
                            
                            array.Add(objet);

                            if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
                                var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
                                
                                zip.CreateEntryFromFile(path, item.TileId + "/normal");
                            }
                        });
                        writer.WriteLine(array.Stringify());
                        
                    }

                    FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                    if(status == FileUpdateStatus.Complete) {
                        var folder = await file.GetParentAsync();
                        await new MessageDialog("Speichern erfolgreich").ShowAsync();
                    } else {
                        await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
                    }

                    Debug.WriteLine(status);
                }
            }
        }
コード例 #16
0
ファイル: ZipArchive.cs プロジェクト: tyty999/peachpie
        /// <summary>
        /// Creates an archive entry or throw an <see cref="InvalidOperationException"/> if already exists.
        /// </summary>
        private ZipArchiveEntry CreateEntryIfNotExists(string entryName)
        {
            if (_archive.GetEntry(entryName) != null)
            {
                throw new InvalidOperationException(string.Format(Resources.Resources.zip_entry_exists, entryName));
            }

            return(_archive.CreateEntry(entryName));
        }
コード例 #17
0
ファイル: Test_OpenXml_Zip.cs プロジェクト: 24/source_04
        public static void Test_OpenXml_Zip_01(string docxFile, string directory, bool useSlash, bool addDirectoryEntry)
        {
            // ok    useSlash = false, addDirectoryEntry = false
            // bad   useSlash = false, addDirectoryEntry = true               le fichier est corrompu
            // ok    useSlash = true,  addDirectoryEntry = true
            // ok    useSlash = true,  addDirectoryEntry = false
            if (zFile.Exists(docxFile))
            {
                zFile.Delete(docxFile);
            }
            int l = directory.Length;

            if (!directory.EndsWith("\\"))
            {
                l++;
            }
            //using (FileStream fs = new FileStream(docxFile, FileMode.OpenOrCreate))
            using (FileStream fs = zFile.Open(docxFile, FileMode.OpenOrCreate))
                using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update, false, Encoding.UTF8))
                {
                    int fileCount      = 0;
                    int directoryCount = 0;
                    foreach (FileSystemInfo file in new DirectoryInfo(directory).EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories))
                    {
                        string entryName = file.FullName.Substring(l);
                        if (useSlash)
                        {
                            entryName = entryName.Replace('\\', '/');
                        }
                        if ((file.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            if (useSlash)
                            {
                                entryName = entryName + "/";
                            }
                            else
                            {
                                entryName = entryName + "\\";
                            }
                            if (addDirectoryEntry)
                            {
                                Trace.WriteLine($"add directory \"{entryName}\"");
                                ZipArchiveEntry entry = zipArchive.CreateEntry(entryName);
                                directoryCount++;
                            }
                        }
                        else
                        {
                            Trace.WriteLine($"add file      \"{entryName}\"");
                            zipArchive.CreateEntryFromFile(file.FullName, entryName);
                            fileCount++;
                        }
                    }
                    Trace.WriteLine($"total {fileCount + directoryCount} entries {fileCount} files {directoryCount} directories");
                }
        }
コード例 #18
0
 /// <summary>
 /// Save an image to zip archive
 /// </summary>
 /// <param name="image">The image to save</param>
 /// <param name="archive">The archive to save to</param>
 public void SaveImage(Image image, ZipArchive archive)
 {
     // Create file in zip
     ZipArchiveEntry imageEntry = archive.CreateEntry(StringResources.PATH_IMAGE_DIR + Path);
     using (Stream stream = imageEntry.Open())
     {
         // Save the image
         image.Save(stream, ImageFormat.Png);
     }
 }
コード例 #19
0
    public void Start(Options options) {
      foreach (var file in options.InputFiles) {
        string fileName = Path.GetFileName(file);
        using (var stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite)) {
          using (var zipFile = new ZipArchive(stream, ZipArchiveMode.Update)) {
            ZipArchiveEntry data = zipFile.Entries.Where(x => x.FullName.Equals("data.xml")).FirstOrDefault();
            ZipArchiveEntry typecache = zipFile.Entries.Where(x => x.FullName.Equals("typecache.xml")).FirstOrDefault();

            string tmp = null;
            XmlDocument doc = new XmlDocument();
            using (var s = new StreamReader(data.Open())) {
              tmp = s.ReadToEnd();
            }
            doc.LoadXml(tmp);
            var primitiveNode = doc.SelectNodes("//PRIMITIVE[contains(.,'GEArtificialAntEvaluator')]");
            if (primitiveNode.Count > 1 || primitiveNode.Count <= 0) {
              Helper.printToConsole("No GEArtificialAntEvaluator found", fileName);
              continue;
            }
            primitiveNode[0].ParentNode.ParentNode.RemoveChild(primitiveNode[0].ParentNode);

            string name = data.FullName;
            data.Delete();
            data = zipFile.CreateEntry(name);
            using (var s = new StreamWriter(data.Open())) {
              doc.Save(s);
            }

            using (var s = new StreamReader(typecache.Open())) {
              tmp = s.ReadToEnd();
            }
            tmp = string.Join(Environment.NewLine, tmp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Where(x => !x.Contains("GrammaticalEvolution")).ToArray());
            name = typecache.FullName;
            typecache.Delete();
            typecache = zipFile.CreateEntry(name);
            using (var s = new StreamWriter(typecache.Open())) {
              s.Write(tmp);
            }
          }
        }
      }
    }
コード例 #20
0
ファイル: ZipRepository.cs プロジェクト: node-net/Node.Net
 public void Set(string key, object value)
 {
     using (FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate))
     {
         using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create))
         {
             var entry = archive.CreateEntry(key);
             Writer.Write(entry.Open(), value);
         }
     }
 }
コード例 #21
0
 private static void AddIfExist(FileInfo file, ZipArchive zip)
 {
     if (file.Exists)
     {
         using var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
         var entry = zip.CreateEntry(file.Name);
         using var entryStream = entry.Open();
         stream.CopyTo(entryStream);
         //zip.CreateEntryFromFile(file.FullName, file.Name);
     }
 }
コード例 #22
0
 /// <inheritdoc />
 public byte[] Compress(byte[] data, string dataName)
 {
     var fileName = string.IsNullOrEmpty(dataName) ? "data.bin" : dataName;
     var output = new MemoryStream();
     using (var archive = new ZipArchive(output, ZipArchiveMode.Create))
     {
         var entry = archive.CreateEntry(fileName, CompressionLevel.Optimal);
         using (var stream = entry.Open())
             stream.Write(data, 0, data.Length);
     }
     return output.ToArray();
 }
コード例 #23
0
        public static void FixupAarClass(string filename, string artName)
        {
            using (var fileStream = new FileStream(filename, FileMode.Open))
                using (var zipArchive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update, true))
                {
                    var entryNames = zipArchive.Entries.Select(zae => zae.FullName).ToList();

                    Console.WriteLine("Found {0} entries in {1}", entryNames.Count, filename);

                    foreach (var entryName in entryNames)
                    {
                        var newName = entryName;

                        // Open the old entry
                        var oldEntry = zipArchive.GetEntry(entryName);
                        // We are only re-adding non empty folders, otherwise we end up with a corrupt zip in mono
                        if (!string.IsNullOrEmpty(oldEntry.Name))
                        {
                            // UGLY WORKAROUND
                            // In the some of the native libraries, there exist multiple .aar files which have a libs/r-classes.jar file.
                            // In Xamarin.Android, there is a Task "CheckDuplicateJavaLibraries" which inspects jar files being pulled in from .aar files
                            // in assemblies to see if there exist any files with the same name but different content, and will throw an error if it finds any.
                            // However, for us, it is perfectly valid to have this scenario and we should not see an error.
                            var newFile = Path.GetFileName(newName);
                            var newDir  = Path.GetDirectoryName(newName);

                            if (newFile.StartsWith("r", StringComparison.InvariantCulture))
                            {
                                newName = newDir + "/" + "r-" + artName + ".jar";
                            }

                            Console.WriteLine("Renaming: {0} to {1}", entryName, newName);

                            // Create a new entry based on our new name
                            var newEntry = zipArchive.CreateEntry(newName);


                            // Copy file contents over if they exist
                            if (oldEntry.Length > 0)
                            {
                                using (var oldStream = oldEntry.Open())
                                    using (var newStream = newEntry.Open())
                                    {
                                        oldStream.CopyTo(newStream);
                                    }
                            }
                        }

                        // Delete the old entry regardless of if it's a folder or not
                        oldEntry.Delete();
                    }
                }
        }
コード例 #24
0
ファイル: AmfProcessing.cs プロジェクト: CNCBrasil/agg-sharp
		/// <summary>
		/// Writes the mesh to disk in a zip container
		/// </summary>
		/// <param name="meshToSave">The mesh to save</param>
		/// <param name="fileName">The file path to save at</param>
		/// <param name="outputInfo">Extra meta data to store in the file</param>
		/// <returns>The results of the save operation</returns>
		public static bool Save(List<MeshGroup> meshToSave, string fileName, MeshOutputSettings outputInfo = null)
		{
			using (Stream stream = File.OpenWrite(fileName))
			using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
			{
				ZipArchiveEntry zipEntry = archive.CreateEntry(Path.GetFileName(fileName));
				using (var entryStream = zipEntry.Open())
				{
					return Save(meshToSave, entryStream, outputInfo);
				}
			}
		}
コード例 #25
0
ファイル: NippsLogHelper.cs プロジェクト: aozkesek/dotNET
        public static bool ZipFiles(string zipFileName, string sourcePath, string fileExt, DateTime startDate, DateTime finishDate)
        {
            NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

            try
            {
                string zipFileNameFull = sourcePath + TranslateZipFileName(zipFileName, fileExt, startDate, finishDate);

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

                using (FileStream zipArchiveStream = File.Create(zipFileNameFull))
                {
                    using (ZipArchive zipArchive = new ZipArchive(zipArchiveStream, ZipArchiveMode.Update))
                    {
                        foreach (string fileName in Directory.GetFiles(sourcePath))
                        {
                            if (fileName.EndsWith(fileExt) && Match(fileName, startDate, finishDate))
                            {
                                string entryName = fileName.Substring(sourcePath.Length);
                                ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(entryName);

                                try
                                {
                                    using (FileStream fileStream = File.OpenRead(fileName))
                                    {
                                        byte[] buffer = new byte[fileStream.Length];
                                        fileStream.Read(buffer, 0, buffer.Length);

                                        try
                                        {
                                            using (Stream stream = zipArchiveEntry.Open())
                                            {
                                                stream.Write(buffer, 0, buffer.Length);
                                                stream.Close();
                                            }
                                        }
                                        catch (Exception ex) { logger.Error(ex); }
                                    }
                                }
                                catch (Exception ex) { logger.Error(ex); }
                            }
                        }

                        return true;
                    }
                }
            }
            catch (Exception ex) { logger.Error(ex); }

            return false;
        }
コード例 #26
0
        private static void AddFilesToArchive(DirectoryInfo source, string path, ZipArchive zipArchive)
        {
            foreach (var s in source.GetFiles())
            {
                var entry = zipArchive.CreateEntry(Path.Combine(path, s.Name), CompressionLevel.NoCompression);
                using (var zipStream = entry.Open())
                using (var fileStream = s.OpenRead())
                    fileStream.CopyTo(zipStream);
            }

            foreach (var s in source.GetDirectories())
                AddFilesToArchive(s, Path.Combine(path, s.Name), zipArchive);
        }
コード例 #27
0
 /// <summary>
 /// Implements <see cref="IFileCompressor.CompressFile(string, string)"/> using the .Net4.5 specific <see cref="ZipArchive"/>
 /// </summary>
 public void CompressFile(string fileName, string archiveFileName)
 {
     using (var archiveStream = new FileStream(archiveFileName, FileMode.Create))
     using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
     using (var originalFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ))
     {
         var zipArchiveEntry = archive.CreateEntry(Path.GetFileName(fileName));
         using (var destination = zipArchiveEntry.Open())
         {
             originalFileStream.CopyTo(destination);
         }
     }
 }
コード例 #28
0
ファイル: PackageBuilder.cs プロジェクト: eerhardt/NuGet3
        private void WriteManifest(ZipArchive package)
        {
            var path = Manifest.GetMetadataValue("id") + ".nuspec";

            WriteOpcManifestRelationship(package, path);

            var entry = package.CreateEntry(path, CompressionLevel.Optimal);

            using (var stream = entry.Open())
            {
                new NuSpecFormatter().Save(Manifest, stream);
            }
        }
コード例 #29
0
ファイル: Container.cs プロジェクト: skipme/DialogMaker
        public string reWriteRecord(string entryName, byte[] data)
        {
            if (string.IsNullOrWhiteSpace(entryName))
            {
                entryName = Guid.NewGuid().ToString();
            }
            ZipArchiveEntry newEntry;

            if (null != (newEntry = linkedArchive.GetEntry(entryName)))
            {
                newEntry.Delete();
                //throw new Exception(string.Format("entry {0} already exists in archive", entryName));
            }

            newEntry = linkedArchive.CreateEntry(entryName, CompressionLevel.Fastest);
            Stream es = newEntry.Open();

            es.Write(data, 0, data.Length);
            es.Close();

            return(entryName);
        }
コード例 #30
0
        public static void FixupAarResource(string filename, string artName)
        {
            using (var fileStream = new FileStream(filename, FileMode.Open))
                using (var zipArchive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update, true))
                {
                    var entryNames = zipArchive.Entries.Select(zae => zae.FullName).ToList();

                    Console.WriteLine("Found {0} entries in {1}", entryNames.Count, filename);

                    foreach (var entryName in entryNames)
                    {
                        var newName = entryName;

                        // Open the old entry
                        var oldEntry = zipArchive.GetEntry(entryName);
                        // We are only re-adding non empty folders, otherwise we end up with a corrupt zip in mono
                        if (!string.IsNullOrEmpty(oldEntry.Name))
                        {
                            var newFile = Path.GetFileName(newName);
                            var newDir  = Path.GetDirectoryName(newName);


                            //Fix R.text in different .aar
                            if (newFile.Contains("R.txt"))
                            {
                                newName = newDir + "/" + "R-" + artName + ".txt";
                            }

                            Console.WriteLine("Renaming: {0} to {1}", entryName, newName);

                            // Create a new entry based on our new name
                            var newEntry = zipArchive.CreateEntry(newName);


                            // Copy file contents over if they exist
                            if (oldEntry.Length > 0)
                            {
                                using (var oldStream = oldEntry.Open())
                                    using (var newStream = newEntry.Open())
                                    {
                                        oldStream.CopyTo(newStream);
                                    }
                            }
                        }

                        // Delete the old entry regardless of if it's a folder or not
                        oldEntry.Delete();
                    }
                }
        }
コード例 #31
0
        private string CreateZip(string[] files)
        {
            var dest = Path.Combine(_tempDir, "test.zip");

            using (var fileStream = new FileStream(dest, FileMode.Create))
                using (var zipStream = new ZipArchiveStream(fileStream, ZipArchiveMode.Create))
                {
                    foreach (var file in files)
                    {
                        zipStream.CreateEntry(file);
                    }
                }

            return(dest);
        }
コード例 #32
0
ファイル: BlobBuilder.cs プロジェクト: amacal/tick-tock
        public byte[] Build()
        {
            using (MemoryStream memory = new MemoryStream())
            {
                using (ZipArchive archive = new ZipArchive(memory, ZipArchiveMode.Create, true))
                {
                    foreach (string file in files.Keys)
                    {
                        archive.CreateEntry(file, CompressionLevel.Fastest);
                    }
                }

                return memory.ToArray();
            }
        }
コード例 #33
0
ファイル: Compression.cs プロジェクト: pparadis/FrenchCoding
 static void Main(string[] args)
 {
     using (FileStream zipToOpen = new FileStream(@"c:\users\exampleuser\release.zip", FileMode.Open))
     {
         using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
         {
             ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
             using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
             {
                 writer.WriteLine("Information about this package.");
                 writer.WriteLine("========================");
             }
         }
     }
 }
コード例 #34
0
        public Stream Export(List<TeamResult> results, Stream excelTemplate)
        {
            using (var z = new ZipArchive(excelTemplate, ZipArchiveMode.Update))
            {
                ZipArchiveEntry sharedString = z.GetEntry("xl/sharedStrings.xml");

                byte[] data;
                using (Stream stream = sharedString.Open())
                {
                    data = new byte[stream.Length];
                    stream.Read(data, 0, (int)stream.Length);
                }

                string content = Encoding.UTF8.GetString(data, 0, data.Length);

                string teamNameFormat = "[$teamName{0}]";
                string teamScoreFormat = "[$teamScore{0}]";
                for (int i = 0; i < results.Count; ++i)
                {
                    content = content.Replace(string.Format(teamNameFormat, (i + 1)), results[i].Name);
                    content = content.Replace(string.Format(teamScoreFormat, (i + 1)), Math.Round(results[i].Score, 2).ToString());
                }

                for (int i = results.Count; i < 200; ++i)
                {
                    string teamName = string.Format(teamNameFormat, (i + 1));
                    if (!content.Contains(teamName))
                    {
                        break;
                    }

                    content = content.Replace(teamName, string.Empty);
                    content = content.Replace(string.Format(teamScoreFormat, (i + 1)), string.Empty);
                }

                sharedString.Delete();

                sharedString = z.CreateEntry("xl/sharedStrings.xml");

                using (StreamWriter stream = new StreamWriter(sharedString.Open()))
                {
                    stream.Write(content);
                }
            }

            return excelTemplate;
        }
コード例 #35
0
ファイル: DBToZip.cs プロジェクト: GitOffice/DataPie
        public static int DataReaderToZip(String zipFileName, IDataReader reader, string tablename)
        {
            Stopwatch watch = Stopwatch.StartNew();
            watch.Start();
            using (FileStream fsOutput = new FileStream(zipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                using (ZipArchive archive = new ZipArchive(fsOutput, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry(tablename + ".csv");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open(), Encoding.UTF8))
                    {
                        for (int i = 0; i < reader.FieldCount; i++)
                        {
                            if (i > 0)
                                writer.Write(',');
                            writer.Write(reader.GetName(i) );
                        }
                        writer.Write(Environment.NewLine);

                        while (reader.Read())
                        {
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                if (i > 0)
                                    writer.Write(',');
                                String v = reader[i].ToString();
                                if (v.Contains(',') || v.Contains('\n') || v.Contains('\r') || v.Contains('"'))
                                {
                                    writer.Write('"');
                                    writer.Write(v.Replace("\"", "\"\""));
                                    writer.Write('"');
                                }
                                else
                                {
                                    writer.Write(v);
                                }
                            }
                            writer.Write(Environment.NewLine);
                        }

                    }
                }

            }
            watch.Stop();
            return Convert.ToInt32(watch.ElapsedMilliseconds / 1000);
        }
コード例 #36
0
ファイル: PackageBuilder.cs プロジェクト: eerhardt/NuGet3
        private HashSet<string> WriteFiles(ZipArchive package)
        {
            var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            foreach (var file in _files)
            {
                var entry = package.CreateEntry(file.Path, CompressionLevel.Optimal);
                using (var stream = entry.Open())
                {
                    file.GetStream().CopyTo(stream);
                }

                extensions.Add(Path.GetExtension(file.Path).Substring(1));
            }

            return extensions;
        }
コード例 #37
0
 public static void Test_ZipArchive_AddEntry_01(string zipFile, string entryName, CompressionLevel compressionLevel = CompressionLevel.Optimal)
 {
     // The first example shows how to create a new entry and write to it by using a stream.
     // FileMode.Open
     using (FileStream fileStream = new FileStream(zipFile, FileMode.OpenOrCreate))
     {
         using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update))
         {
             ZipArchiveEntry readmeEntry = archive.CreateEntry(entryName, compressionLevel);
             using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
             {
                 writer.WriteLine("Information about this package.");
                 writer.WriteLine("========================");
             }
         }
     }
 }
コード例 #38
0
ファイル: Test_ZipArchive.cs プロジェクト: labeuze/source
 public static void Test_ZipArchive_AddEntry_01(string zipFile, string entryName, CompressionLevel compressionLevel = CompressionLevel.Optimal)
 {
     // The first example shows how to create a new entry and write to it by using a stream.
     // FileMode.Open
     using (FileStream fileStream = new FileStream(zipFile, FileMode.OpenOrCreate))
     {
         using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update))
         {
             ZipArchiveEntry readmeEntry = archive.CreateEntry(entryName, compressionLevel);
             using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
             {
                 writer.WriteLine("Information about this package.");
                 writer.WriteLine("========================");
             }
         }
     }
 }
コード例 #39
0
        static void Main(string[] args)
        {
            using (System.IO.Compression.ZipArchive zip = ZipFile.Open("results.zip", ZipArchiveMode.Create))
            {
                for (int i = 0; i < 2; ++i)
                {
                    var inputFilter             = string.Format(CultureInfo.InvariantCulture, String.Format("{0}_*", i));
                    HashSet <string> inputFiles = CollectFiles(LocalStoragePath, inputFilter);

                    zip.CreateEntry(String.Format("{0}/", i));
                    foreach (var file in inputFiles)
                    {
                        zip.CreateEntryFromFile(file, String.Format("{0}/{1}", i, Path.GetFileName(file)));
                    }
                }
            }
        }
コード例 #40
0
ファイル: Zip.cs プロジェクト: CodeComb/Package
 public static void Compress(string path, string dest, CompressionLevel level = CompressionLevel.Optimal)
 {
     using (var stream = new FileStream(dest, FileMode.OpenOrCreate))
     using (var archive = new ZipArchive(stream, ZipArchiveMode.Update))
     {
         var files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
         foreach (var x in files)
         {
             var entry = archive.CreateEntry(x.Replace(path, "").Trim('/').Trim('\\'), level);
             using (StreamWriter writer = new StreamWriter(entry.Open()))
             {
                 var file = new FileStream(x, FileMode.Open);
                 file.CopyTo(writer.BaseStream);
             }
         }
     }
 }
コード例 #41
0
        protected void CreateFileZip()
        {
            string dirRoot = Server.MapPath("~/file");

            //get a list of files
            string[] filesToZip = Directory.GetFiles(dirRoot, "*.*", SearchOption.AllDirectories);
            using (MemoryStream zipMS = new MemoryStream())
            {
                using (System.IO.Compression.ZipArchive zipArchive = new System.IO.Compression.ZipArchive(zipMS, System.IO.Compression.ZipArchiveMode.Create, true))
                {
                    //loop through files to add
                    foreach (string fileToZip in filesToZip)
                    {
                        //exclude some files? -I don't want to ZIP other .zips in the folder.
                        if (new FileInfo(fileToZip).Extension == ".zip")
                        {
                            continue;
                        }

                        //exclude some file names maybe?
                        if (fileToZip.Contains("node_modules"))
                        {
                            continue;
                        }

                        //read the file bytes
                        byte[] fileToZipBytes = System.IO.File.ReadAllBytes(fileToZip);
                        //create the entry - this is the zipped filename
                        //change slashes - now it's VALID
                        System.IO.Compression.ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(fileToZip.Replace(dirRoot, "").Replace('\\', '/'));
                        //add the file contents
                        using (Stream zipEntryStream = zipFileEntry.Open())
                            using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream))
                            {
                                zipFileBinary.Write(fileToZipBytes);
                            }
                    }
                }
                using (FileStream finalZipFileStream = new FileStream(Server.MapPath("~/file/DanhSachBangKe.zip"), FileMode.Create))
                {
                    zipMS.Seek(0, SeekOrigin.Begin);
                    zipMS.CopyTo(finalZipFileStream);
                }
            }
        }
コード例 #42
0
ファイル: ZipTasks.cs プロジェクト: codekaizen/swifttailer
        public static void ZipGroup(LogGroup logGroup, string saveLocation, IProgressProvider progressProvider)
        {
            Trace.WriteLine("task started");
            progressProvider.ProgressBarValue = 0;
            using (var ms = new FileStream(saveLocation, FileMode.CreateNew))
            {
                // create the archive to go into the file
                using (var zip = new ZipArchive(ms, ZipArchiveMode.Create))
                {
                    var progressFactor = 100 / logGroup.Logs.Count;

                    // add each log to the archive
                    foreach (var log in logGroup.Logs)
                    {
                        if (!File.Exists(log.Filename))
                            continue;

                        progressProvider.ProgressText = $"Processing {log.Filename}...";

                        // create the entry
                        var entry = zip.CreateEntry(Path.GetFileName(log.Filename), CompressionLevel.Fastest);

                        // fill the entry
                        using (var entryStream = entry.Open())
                        {
                            using (
                                var logFileStream = File.Open(log.Filename, FileMode.Open, FileAccess.Read,
                                    FileShare.ReadWrite))
                            {
                                var fileBytes = new byte[logFileStream.Length];
                                logFileStream.Read(fileBytes, 0, fileBytes.Length);
                                using (var logStream = new MemoryStream(fileBytes))
                                {
                                    logStream.CopyTo(entryStream);
                                    progressProvider.ProgressBarValue += progressFactor;
                                }
                            }
                        }
                    }
                }
            }

            progressProvider.ProgressText = string.Empty;
            progressProvider.ProgressBarValue = 0;
        }
コード例 #43
0
        public static async System.Threading.Tasks.Task <System.Byte[]> CreateZipArchiveAsync(System.Collections.Generic.Dictionary <System.String, System.Byte[]> Files)
        {
            if ((Files == null) || (Files.Count == 0))
            {
                return(null);
            }

            using (System.IO.MemoryStream MemoryStream = new System.IO.MemoryStream())
            {
                using (System.IO.Compression.ZipArchive ZipArchive = new System.IO.Compression.ZipArchive(MemoryStream, System.IO.Compression.ZipArchiveMode.Create, false))
                    foreach (System.Collections.Generic.KeyValuePair <System.String, System.Byte[]> File in Files)
                    {
                        using (System.IO.Stream Stream = ZipArchive.CreateEntry(File.Key).Open())
                            await Stream.WriteAsync(File.Value, 0, File.Value.Length);
                    }
                return(MemoryStream.ToArray());
            }
        }
コード例 #44
0
        internal static void CopyHeaders(CompressionLevel compression, ZipArchive package, DataCopier copier, StorageEnvironmentOptions storageEnvironmentOptions)
        {
            foreach (var headerFileName in HeaderAccessor.HeaderFileNames)
            {
                var header = stackalloc FileHeader[1];

                if (!storageEnvironmentOptions.ReadHeader(headerFileName, header))
                    continue;

                var headerPart = package.CreateEntry(headerFileName, compression);
                Debug.Assert(headerPart != null);

                using (var headerStream = headerPart.Open())
                {
                    copier.ToStream((byte*)header, sizeof(FileHeader), headerStream);
                }
            }
        }
コード例 #45
0
ファイル: Zip.cs プロジェクト: CMSSudhaus/buildeploy
        public override bool Execute()
        {
            using (var stream = File.Create(ZipFileName))
                using (var archive = new System.IO.Compression.ZipArchive(stream, ZipArchiveMode.Create))
                {
                    foreach (var item in Files)
                    {
                        string filePath = item.ItemSpec;
                        var    entry    = archive.CreateEntry(Utils.MakeRelativePath(WorkingDirectory, filePath));

                        using (var inputStream = File.OpenRead(filePath))
                            using (var outStream = entry.Open())
                            {
                                inputStream.CopyTo(outStream);
                            }
                    }
                }

            return(true);
        }
コード例 #46
0
        public void AddOrUpdateItem(string name, byte[] data)
        {
            name = name ?? throw new ArgumentNullException(nameof(name));

            ZipArchiveEntry entry;

            if (!ItemExists(name))
            {
                entry = _archive.CreateEntry(name);
            }
            else
            {
                entry = _archive.GetEntry(name);
            }

            using (Stream wr = entry.Open())
            {
                wr.Write(data, 0, data.Length);
            }
        }
コード例 #47
0
ファイル: Zipper.cs プロジェクト: justinjstark/DataTricks
        public byte[] ZipFiles(IEnumerable <FileToZip> files)
        {
            MemoryStream memoryStream;

            using (memoryStream = new MemoryStream())
                using (var zipArchive = new System.IO.Compression.ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    foreach (var file in files)
                    {
                        var newFile = zipArchive.CreateEntry(Path.Combine(file.Directory ?? "", file.Name));

                        using (var newFileStream = newFile.Open())
                            using (var binaryWriter = new BinaryWriter(newFileStream))
                            {
                                binaryWriter.Write(file.Contents);
                            }
                    }
                }

            return(memoryStream.ToArray());
        }
コード例 #48
0
        /// <summary>
        /// Reading from an excel template , entering data in it and write back to a file
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public async Task <StorageFile> WriteToFile(string filename, StorageFile targetfile)
        {
            //StorageFile targetfile = null;

            try
            {
                var exceltemplatestream = Assembly.Load(new AssemblyName("ExcelManager")).GetManifestResourceStream(@"ExcelManager.Resources.ExcelTemplateFile.xlsx");

                System.IO.Compression.ZipArchive zipArchiveExcelTemplate = new System.IO.Compression.ZipArchive(exceltemplatestream);

                //Data Builder Code
                ExcelXmlBuilder excelbuilder = new ExcelXmlBuilder();
                XmlDocument     xstyleDoc = null;
                string          sheet2string = "", sheet1string;
                List <Cell>     sheetcells = new List <Cell>(ExcelSheet.Cells);

                var styles    = zipArchiveExcelTemplate.Entries.FirstOrDefault(x => x.FullName == "xl/styles.xml");
                var styledata = GetByteArrayFromStream(styles.Open());
                xstyleDoc    = GetStyleXDoc(styledata);
                sheet1string = excelbuilder.BuildSheetXML(ExcelSheet, ref xstyleDoc);

                if (ExcelSheet2 != null && ExcelSheet2.Cells != null && ExcelSheet2.Cells.Count > 0)
                {
                    sheet2string = excelbuilder.BuildSheetXML(ExcelSheet2, ref xstyleDoc, ExcelSheet.Cells.Count);
                    sheetcells.AddRange(ExcelSheet2.Cells);
                }

                using (var zipStream = await targetfile.OpenStreamForWriteAsync())
                {
                    using (System.IO.Compression.ZipArchive newzip = new System.IO.Compression.ZipArchive(zipStream, ZipArchiveMode.Create))
                    {
                        foreach (var file in zipArchiveExcelTemplate.Entries)
                        {
                            System.IO.Compression.ZipArchiveEntry entry = newzip.CreateEntry(file.FullName);
                            using (Stream ZipFile = entry.Open())
                            {
                                byte[] data = null;
                                if (file.FullName == "xl/sharedStrings.xml")
                                {
                                    data = Encoding.UTF8.GetBytes(excelbuilder.BuildSharedXML(sheetcells));
                                    ZipFile.Write(data, 0, data.Length);
                                }
                                else if (file.FullName == "xl/worksheets/sheet1.xml")
                                {
                                    data = Encoding.UTF8.GetBytes(sheet1string);
                                    ZipFile.Write(data, 0, data.Length);
                                }
                                else if (file.FullName == "xl/worksheets/sheet2.xml" && sheet2string != "")
                                {
                                    data = Encoding.UTF8.GetBytes(sheet2string);
                                    ZipFile.Write(data, 0, data.Length);
                                }
                                else if (file.FullName == "xl/styles.xml")
                                {
                                    if (xstyleDoc != null)
                                    {
                                        data = Encoding.UTF8.GetBytes(xstyleDoc.GetXml().Replace("xmlns=\"\"", ""));
                                        ZipFile.Write(data, 0, data.Length);
                                    }
                                }
                                else
                                {
                                    data = GetByteArrayFromStream(file.Open());
                                    ZipFile.Write(data, 0, data.Length);
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            return(targetfile);
        }
コード例 #49
0
ファイル: ZipFile.cs プロジェクト: stevenlius/corefx
        private static void DoCreateFromDirectory(String sourceDirectoryName, String destinationArchiveFileName,
                                                  CompressionLevel?compressionLevel, Boolean includeBaseDirectory,
                                                  Encoding entryNameEncoding)
        {
            // Rely on Path.GetFullPath for validation of sourceDirectoryName and destinationArchive

            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pluggable component that completely encapsulates the meaning of compressionLevel.

            sourceDirectoryName        = Path.GetFullPath(sourceDirectoryName);
            destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName);

            using (ZipArchive archive = Open(destinationArchiveFileName, ZipArchiveMode.Create, entryNameEncoding))
            {
                bool directoryIsEmpty = true;

                //add files and directories
                DirectoryInfo di = new DirectoryInfo(sourceDirectoryName);

                string basePath = di.FullName;

                if (includeBaseDirectory && di.Parent != null)
                {
                    basePath = di.Parent.FullName;
                }

                // Windows' MaxPath (260) is used as an arbitrary default capacity, as it is likely
                // to be greater than the length of typical entry names from the file system, even
                // on non-Windows platforms. The capacity will be increased, if needed.
                const int DefaultCapacity = 260;
                char[]    entryNameBuffer = ArrayPool <char> .Shared.Rent(DefaultCapacity);

                try
                {
                    foreach (FileSystemInfo file in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                    {
                        directoryIsEmpty = false;

                        Int32 entryNameLength = file.FullName.Length - basePath.Length;
                        Debug.Assert(entryNameLength > 0);

                        if (file is FileInfo)
                        {
                            // Create entry for file:
                            String entryName = EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer);
                            ZipFileExtensions.DoCreateEntryFromFile(archive, file.FullName, entryName, compressionLevel);
                        }
                        else
                        {
                            // Entry marking an empty dir:
                            DirectoryInfo possiblyEmpty = file as DirectoryInfo;
                            if (possiblyEmpty != null && IsDirEmpty(possiblyEmpty))
                            {
                                // FullName never returns a directory separator character on the end,
                                // but Zip archives require it to specify an explicit directory:
                                String entryName = EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer, appendPathSeparator: true);
                                archive.CreateEntry(entryName);
                            }
                        }
                    }  // foreach

                    // If no entries create an empty root directory entry:
                    if (includeBaseDirectory && directoryIsEmpty)
                    {
                        archive.CreateEntry(EntryFromPath(di.Name, 0, di.Name.Length, ref entryNameBuffer, appendPathSeparator: true));
                    }
                }
                finally
                {
                    ArrayPool <char> .Shared.Return(entryNameBuffer);
                }
            } // using
        }     // DoCreateFromDirectory
コード例 #50
0
        public DocumentData GetAllAvaliableAttachmentsForJob(List <long> jobId)
        {
            DocumentData        documentData     = null;
            List <DocumentData> documentDataList = new List <DocumentData>();
            List <Task>         tasks            = new List <Task>();

            foreach (var selectedJob in jobId)
            {
                tasks.Add(Task.Factory.StartNew(() =>
                {
                    var attachmentList = _commands.GetAttachmentsByJobId(ActiveUser, selectedJob);
                    if (attachmentList != null && attachmentList.Count > 0)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (var archive = new System.IO.Compression.ZipArchive(ms, ZipArchiveMode.Create, true))
                            {
                                foreach (var file in attachmentList)
                                {
                                    var entry = archive.CreateEntry(file.AttFileName, CompressionLevel.Fastest);
                                    using (var zipStream = entry.Open())
                                    {
                                        zipStream.Write(file.AttData, 0, file.AttData.Length);
                                    }
                                }
                            }

                            documentDataList.Add(
                                new DocumentData()
                            {
                                DocumentContent = ms.ToArray(),
                                ContentType     = "application/zip",
                                DocumentName    = string.Format("documents_{0}.zip", selectedJob)
                            });
                        }
                    }
                }));
            }

            if (tasks.Count > 0)
            {
                Task.WaitAll(tasks.ToArray());
            }
            documentDataList = documentDataList.Where(x => x != null).Any() ? documentDataList.Where(x => x != null).ToList() : new List <DocumentData>();
            if (documentDataList != null && documentDataList.Count > 1)
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                    {
                        foreach (var jobDocument in documentDataList)
                        {
                            var entry = archive.CreateEntry(jobDocument.DocumentName, CompressionLevel.Fastest);
                            using (var zipStream = entry.Open())
                            {
                                zipStream.Write(jobDocument.DocumentContent, 0, jobDocument.DocumentContent.Length);
                            }
                        }
                    }

                    documentData = new DocumentData();
                    documentData.DocumentContent = memoryStream.ToArray();
                    documentData.DocumentName    = string.Format("{0}.zip", "ConsolidatedDocuments");
                    documentData.ContentType     = "application/zip";
                }
            }
            else if (documentDataList != null && documentDataList.Count == 1)
            {
                return(documentDataList[0]);
            }

            return(documentData);
        }