• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Compression.ZipArchive类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IO.Compression.ZipArchive的典型用法代码示例。如果您正苦于以下问题:C# ZipArchive类的具体用法?C# ZipArchive怎么用?C# ZipArchive使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ZipArchive类属于System.IO.Compression命名空间,在下文中一共展示了ZipArchive类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetDataDescriptors

 public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
   List<ResourceRegressionDataDescriptor> descriptorList = new List<ResourceRegressionDataDescriptor>();
   descriptorList.Add(new ChemicalOne());
   descriptorList.Add(new Housing());
   descriptorList.Add(new Tower());
   descriptorList.Add(new Powermeter());
   var solutionsArchiveName = GetResourceName(FileName + @"\.zip");
   if (!String.IsNullOrEmpty(solutionsArchiveName)) {
     using (var solutionsZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(solutionsArchiveName), ZipArchiveMode.Read)) {
       IList<string> entries = new List<string>();
       foreach (var curEntry in solutionsZipFile.Entries) {
         entries.Add(curEntry.Name);
       }
       foreach (var entry in entries.OrderBy(x => x)) {
         string prettyName = Path.GetFileNameWithoutExtension(entry);
         ResourceRegressionDataDescriptor desc = descriptorList.Where(x => x.Name.Equals(prettyName)).FirstOrDefault();
         if (desc != null) {
           desc.ResourceName = entry;
           yield return desc;
         } else
           throw new ArgumentNullException("No Descriptor could be found for this entry.");
       }
     }
   }
 }
开发者ID:thunder176,项目名称:HeuristicLab,代码行数:25,代码来源:RealWorldRegressionInstanceProvider.cs


示例2: UnZippingFiles

        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="dirPath">要解压到的路径</param>
        /// <param name="input">压缩文件数据</param>
        internal static void UnZippingFiles(string dirPath, byte[] input)
        {
            //备份文件到dirPath下Backup文件夹下
            ZippingBackupFiles(dirPath, dirPath + "Backup\\");
            //覆盖文件
            using (var zipStream = new MemoryStream(input))//将压缩文件信息初始化到内存流
            {
                using (var source = new ZipArchive(zipStream, ZipArchiveMode.Read))//读取压缩文件
                {
                    foreach (var entry in source.Entries)
                    {
                        var fullPath = Path.GetFullPath(dirPath + entry.FullName);
                        if (fullPath.EndsWith("\\"))
                        {
                            if (!Directory.Exists(fullPath))
                            {
                                Directory.CreateDirectory(fullPath);
                            }
                        }
                        else
                        {
                            using (var stream = entry.Open())
                            {
                                using (FileStream fileStream = File.Open(fullPath, FileMode.Create))
                                {
                                    stream.CopyTo(fileStream);
                                }
                            }
                        }
                    }

                }
            }
        }
开发者ID:AnchoretTeam,项目名称:AppUpdate,代码行数:39,代码来源:FileZipHelper.cs


示例3: GetRootFilePathAsync

        public static async System.Threading.Tasks.Task<string> GetRootFilePathAsync(ZipArchive epubArchive)
        {
            //Checking if file exist
            const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml";

            ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH);
            string full_path = string.Empty;

            if (containerFileEntry == null)
                throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH));

            //Loading container.xml to memmory...
            using (Stream containerStream = containerFileEntry.Open())
            {
                // ...and trying to parse it in order to get the full path to the .opf file, like full-path="SomeFolder/SomeFileWithContent.opf"
                full_path = await XmlUtils.GetFilePathAttributeAsync(containerStream);
            }
            //Checking if the problem exist...
            if (full_path == "full-path attribute not found" || full_path == "Yes, rootfile not found...")
            {
                Debug.WriteLine(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path));
                throw new Exception(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path));
            }
                
            return full_path;

            //Initial code sucks and is not compatible with Win 8.1 runtime framework
            /*
            xmlNamespaceManager.AddNamespace("cns", "urn:oasis:names:tc:opendocument:xmlns:container");
            XmlNode rootFileNode = containerDocument.DocumentElement.SelectSingleNode("/cns:container/cns:rootfiles/cns:rootfile", xmlNamespaceManager);
            return rootFileNode.Attributes["full-path"].Value;
            */
        }
开发者ID:fedorinoGore,项目名称:bookScriptorW10,代码行数:33,代码来源:RootFilePathReader.cs


示例4: Update

 /// <summary>
 /// Downloads the specified web driver version.
 /// </summary>
 /// <param name="version">The version to download.</param>
 protected override void Update(string version)
 {
     using (var client = new WebClient())
     using (var stream = client.OpenRead("http://chromedriver.storage.googleapis.com/" + version + "/chromedriver_win32.zip"))
     using (var archive = new ZipArchive(stream))
         archive.ExtractToDirectory(Path.Combine(ParentPath, version));
 }
开发者ID:stuartleeks,项目名称:BrowserBoss,代码行数:11,代码来源:ChromeWebDriverSetup.cs


示例5: ZipRecursive

        public static void ZipRecursive(
            string rootDirectoryPath,
            DirectoryInfo currentDirectoryInfo, 
            ZipArchive archive, 
            TextWriter hashWriter, 
            string hashName = ConstDefaultHashName)
        {
            rootDirectoryPath = NormalizePath(rootDirectoryPath);
            foreach (var file in currentDirectoryInfo.GetFiles())
            {
                var entryName = file.FullName.Substring(rootDirectoryPath.Length);

                using (var reader = file.OpenRead())
                {
                    var hash = AddToArchive(entryName, reader, archive, hashName);
                    hashWriter.WriteLine(HashEntryFormat, hash, entryName);
                    Serilog.Log.Verbose("Added {filePath} to zip archive.  MD5: {md5}", file.FullName, hash);
                }
            }

            // recurse
            foreach (var directory in currentDirectoryInfo.GetDirectories())
            {
                ZipRecursive(rootDirectoryPath, directory, archive, hashWriter, hashName);
            }
        }
开发者ID:GalenHealthcare,项目名称:Galen.Ef.Deployer,代码行数:26,代码来源:ZipUtility.cs


示例6: Convert

        public BitmapImage Convert([CanBeNull] string id) {
            if (id == null) id = @"_";

            BitmapImage bi;
            if (Cache.TryGetValue(id, out bi)) return bi;

            if (_archive == null) {
                _archive = new ZipArchive(new MemoryStream(BinaryResources.Flags));
            }

            var entryStream = (_archive.GetEntry(id) ?? _archive.GetEntry(@"_"))?.Open();
            if (entryStream == null) {
                return null;
            }

            bi = new BitmapImage();
            bi.BeginInit();
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.StreamSource = entryStream.ReadAsMemoryStream();
            bi.EndInit();
            bi.Freeze();

            Cache[id] = bi;
            return bi;
        }
开发者ID:gro-ove,项目名称:actools,代码行数:25,代码来源:CountryIdToImageConverter.cs


示例7: ModelInfo

        /// <summary>
        /// Initializes a new instance of the <see cref="ModelInfo"/> class.
        /// </summary>
        /// <param name="fileInfo">The model file info.</param>
        /// <exception cref="System.ArgumentNullException">fileInfo</exception>
        /// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
        /// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
        public ModelInfo(FileInfo fileInfo) {
            if (fileInfo == null)
                throw new ArgumentNullException("fileInfo");

            if (!fileInfo.Exists)
                throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);

            File = fileInfo;
            Name = Path.GetFileNameWithoutExtension(fileInfo.Name);

            try {

                using (var zip = new ZipArchive(fileInfo.OpenRead(), ZipArchiveMode.Read)) {
                    foreach (var entry in zip.Entries) {
                        if (entry.Name != ArtifactProvider.ManifestEntry) 
                            continue;

                        using (var stream = entry.Open()) {
                            Manifest = (Properties)Properties.Deserialize(stream);
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                throw new InvalidFormatException("Unable to load the specified model file.", ex);
            }
        }
开发者ID:lovethisgame,项目名称:SharpNL,代码行数:34,代码来源:ModelInfo.cs


示例8: CheckAndUpdateIfNeededInner

        protected override async Task<bool> CheckAndUpdateIfNeededInner() {
            if (InstalledVersion == null) return false;

            var data = await CmApiProvider.GetDataAsync($"locales/update/{SettingsHolder.Locale.LocaleName}/{InstalledVersion}");
            if (data == null) {
                LatestError = ToolsStrings.BaseUpdater_CannotDownloadInformation;
                Logging.Warning("Cannot get locales/update");
                return false;
            }

            if (data.Length == 0) {
                return false;
            }

            try {
                LocalePackageManifest manifest;
                using (var memory = new MemoryStream(data))
                using (var updateZip = new ZipArchive(memory)) {
                    manifest = LocalePackageManifest.FromArchive(updateZip);
                    if (manifest == null) throw new Exception("Manifest is missing");
                }

                var package = FilesStorage.Instance.GetFilename("Locales", manifest.Id + ".pak");
                await FileUtils.WriteAllBytesAsync(package, data);
                Logging.Write("Locale updated");

                InstalledVersion = manifest.Version;
                return true;
            } catch (Exception e) {
                Logging.Warning("Cannot update locale: " + e);
                return false;
            }
        }
开发者ID:gro-ove,项目名称:actools,代码行数:33,代码来源:LocaleUpdater.cs


示例9: LoadAndInstall

        private async Task<bool> LoadAndInstall() {
            if (_isInstalling) return false;
            _isInstalling = true;

            try {
                var data = await CmApiProvider.GetDataAsync("data/latest");
                if (data == null) throw new InformativeException(ToolsStrings.AppUpdater_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks);

                string installedVersion = null;
                await Task.Run(() => {
                    var location = FilesStorage.Instance.Combine(FilesStorage.DataDirName);
                    Directory.Delete(location, true);

                    using (var stream = new MemoryStream(data, false))
                    using (var archive = new ZipArchive(stream)) {
                        installedVersion = VersionFromData(archive.GetEntry(@"Manifest.json").Open().ReadAsStringAndDispose());
                        archive.ExtractToDirectory(location);
                    }
                });

                InstalledVersion = installedVersion;
                Logging.Write("Data loaded: " + InstalledVersion);
                return true;
            } catch (Exception e) {
                NonfatalError.Notify(ToolsStrings.ContentSyncronizer_CannotLoadContent, ToolsStrings.ContentSyncronizer_CannotLoadContent_Commentary, e);
            } finally {
                _isInstalling = false;
            }

            return false;
        }
开发者ID:gro-ove,项目名称:actools,代码行数:31,代码来源:DataUpdater.cs


示例10: ImportFiles

        private void ImportFiles(ZipArchive file, string path)
        {
            var enumerable = file.Entries.Where(a => a.FullName.StartsWith("data/"));

            foreach (var zipArchiveEntry in enumerable)
            {
                var directoryName = Path.GetDirectoryName(zipArchiveEntry.FullName);
                if (directoryName != null)
                {
                    string virtualPath = "." +
                                         (directoryName.Replace("\\", "/") + "/" +
                                          Path.GetFileNameWithoutExtension(zipArchiveEntry.FullName)).Substring(4);
                    var extension = Path.GetExtension(zipArchiveEntry.FullName);
                    if (extension != null && !Root.Information.DeletedFiles.Contains(virtualPath))
                    {
                        string hash = extension.Substring(1);

                        if (Root.Children.All(a => a.VirtualPath != virtualPath))
                            Root.Children.Add(new BackupFile
                                                  {
                                                      Name =
                                                          Path.GetFileNameWithoutExtension(
                                                              Path.GetFileName(zipArchiveEntry.FullName)),
                                                      FileHash = hash,
                                                      VirtualPath = virtualPath,
                                                      ArchivePath = path
                                                  });
                    }
                }
            }
        }
开发者ID:pdelvo,项目名称:IncrementalBackup,代码行数:31,代码来源:BackupStatus.cs


示例11: CreateTestPackageStream

        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;
        }
开发者ID:ZhiYuanHuang,项目名称:NuGetGallery,代码行数:34,代码来源:PackageMetadataFacts.cs


示例12: ButtonRestore_Click

		private async void ButtonRestore_Click(object sender, RoutedEventArgs e)
		{
			var selected = ListBoxBackups.SelectedItem as BackupFile;
			if(selected != null)
			{
				var result =
					await
					Helper.MainWindow.ShowMessageAsync("Restore backup " + selected.DisplayName,
					                                   "This can not be undone! Make sure you have a current backup (if necessary). To create one, CANCEL and click \"CREATE NEW\".",
					                                   MessageDialogStyle.AffirmativeAndNegative);
				if(result == MessageDialogResult.Affirmative)
				{
					var archive = new ZipArchive(selected.FileInfo.OpenRead(), ZipArchiveMode.Read);
					archive.ExtractToDirectory(Config.Instance.DataDir, true);
					Config.Load();
					Config.Save();
					DeckList.Load();
					DeckList.Save();
					DeckStatsList.Load();
					DeckStatsList.Save();
					DefaultDeckStats.Load();
					DefaultDeckStats.Save();
					Helper.MainWindow.ShowMessage("Success", "Please restart HDT for this to take effect.");
				}
			}
		}
开发者ID:nikolasferreira,项目名称:Hearthstone-Deck-Tracker,代码行数:26,代码来源:TrackerBackups.xaml.cs


示例13: ProcessFolder

        static void ProcessFolder(XElement folder, ZipArchive theZip, string folderRelativePath)
        {
            string targetDirectory = (string)folder.Attribute("Name");
            string currentRelativePath = AppendRelativePath(folderRelativePath, targetDirectory);

            Console.WriteLine("Processing folder " + currentRelativePath);

            foreach (var component in folder.Elements(Namespace + ElementNameComponent))
            {
                foreach (var file in component.Elements(Namespace + ElementNameFile))
                {
                    string source = (string)file.Attribute("Source");
                    string name = (string)file.Attribute("Name");

                    theZip.CreateEntryFromFile(RelativePathToolToSetupFolder + source,
                        AppendRelativePath(currentRelativePath, name),
                        CompressionLevel.Optimal);
                }
            }

            foreach (var secondaryFolder in folder.Elements(Namespace + ElementNameDirectory))
            {
                ProcessFolder(secondaryFolder, theZip, currentRelativePath);
            }
        }
开发者ID:ichengzi,项目名称:SharpDevelop,代码行数:25,代码来源:Program.cs


示例14: InstallPackageAsync

        public async override Task<bool> InstallPackageAsync(Packaging.Core.PackageIdentity packageIdentity, System.IO.Stream packageStream,
            INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if (!packageStream.CanSeek)
            {
                throw new ArgumentException(NuGet.ProjectManagement.Strings.PackageStreamShouldBeSeekable);
            }

            nuGetProjectContext.Log(MessageLevel.Info, Strings.InstallingPackage, packageIdentity);

            packageStream.Seek(0, SeekOrigin.Begin);
            var zipArchive = new ZipArchive(packageStream);
            PackageReader packageReader = new PackageReader(zipArchive);
            var packageSupportedFrameworks = packageReader.GetSupportedFrameworks();
            var projectFrameworks = _project.GetSupportedFrameworksAsync(token)
                .Result
                .Select(f => NuGetFramework.Parse(f.FullName));

            var args = new Dictionary<string, object>();
            args["Frameworks"] = projectFrameworks.Where(
                projectFramework =>
                    IsCompatible(projectFramework, packageSupportedFrameworks)).ToArray();
            await _project.InstallPackageAsync(
                new NuGetPackageMoniker
                {
                    Id = packageIdentity.Id,
                    Version = packageIdentity.Version.ToNormalizedString()
                },
                args,
                logger: null,
                progress: null,
                cancellationToken: token);
            return true;
        }
开发者ID:mauroa,项目名称:NuGet.VisualStudioExtension,代码行数:34,代码来源:ProjectKNuGetProject.cs


示例15: ExtractEntries

        public string[] ExtractEntries(string sourceArchiveFileName, string destinationDirectoryName)
        {
            using (var archiveStream = _fileSystem.OpenFile(sourceArchiveFileName, FileMode.Open, FileAccess.Read))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read))
            {
                foreach (var entry in archive.Entries)
                {
                    var path = PathHelper.Combine(destinationDirectoryName, entry.FullName);
                    if (string.IsNullOrEmpty(entry.Name))
                    {
                        // is a directory
                        if (!_fileSystem.DirExists(path))
                            _fileSystem.CreateDir(path);
                        continue;
                    }
                    else
                    {
                        var dir = PathHelper.GetParent(path);
                        if (!_fileSystem.DirExists(dir))
                            _fileSystem.CreateDir(dir);
                    }

                    using (var entryStream = entry.Open())
                    {
                        using (var fileStream = _fileSystem.OpenFile(path, FileMode.Create, FileAccess.Write))
                        {
                            entryStream.CopyTo(fileStream);
                            fileStream.Flush();
                        }
                    }
                }
                var entries = archive.Entries.Select(x => x.FullName).ToArray();
                return entries;
            }
        }
开发者ID:LazyTarget,项目名称:Lux,代码行数:35,代码来源:ZipFileCompressorMock.cs


示例16: ReduceXap_CreateNewFile_Test

        public void ReduceXap_CreateNewFile_Test()
        {
            var fileSystem = Substitute.For<IFileSystem>();
            var console = new StringWriter();

            CreateFakeInputXap(fileSystem, ZipArchiveMode.Read, "A", "B").
                AddResourceAssemblyPart("en", "A").
                AddResourceAssemblyPart("en-US", "A").
                AddResourceAssemblyPart("en", "B");

            CreateFakeSourceXap(fileSystem, "A", "C");

            MemoryStream outputStream = new MemoryStream();
            fileSystem.FileExists("Output.xap").Returns(true);
            fileSystem.OpenArchive("Output.xap", ZipArchiveMode.Create).Returns(new ZipArchive(outputStream, ZipArchiveMode.Create, true));

            var options = new Options()
            {
                Input = "Input.xap",
                Sources = new[] { "Source.xap" },
                Output = "Output.xap"
            };

            var builder = new XapBuilder();
            builder.AddAssemblyPart("A", 1000);

            var minifier = new XapMinifier(fileSystem, console);
            minifier.ReduceXap(options);

            var output = new ZipArchive(outputStream, ZipArchiveMode.Read, true);
            Assert.AreEqual(3, output.Entries.Count);
            Assert.IsNotNull(output.GetEntry("B.dll"));
            Assert.IsNotNull(output.GetEntry("en\\B.resources.dll"));
        }
开发者ID:Thorarin,项目名称:XapReduce,代码行数:34,代码来源:XapMinifierTests.cs


示例17: AddDirectoryToArchiveIncludesDirectoryTreeInArchive

        public void AddDirectoryToArchiveIncludesDirectoryTreeInArchive()
        {
            // Arrange
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create);

            var emptyDir = new Mock<DirectoryInfoBase>();
            emptyDir.SetupGet(d => d.Name).Returns("empty-dir");
            emptyDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[0]);
            var subDir = new Mock<DirectoryInfoBase>();
            subDir.SetupGet(d => d.Name).Returns("site");
            subDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { emptyDir.Object, CreateFile("home.aspx", "home content"), CreateFile("site.css", "some css") });

            var directoryInfo = new Mock<DirectoryInfoBase>();
            directoryInfo.SetupGet(f => f.Name).Returns("zip-test");
            directoryInfo.Setup(f => f.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { subDir.Object, CreateFile("zero-length-file", ""), CreateFile("log.txt", "log content") });

            // Act
            zip.AddDirectory(directoryInfo.Object, "");

            // Assert
            zip.Dispose();
            File.WriteAllBytes(@"d:\foo.zip", stream.ToArray());
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(5, zip.Entries.Count);
            AssertZipEntry(zip, "log.txt", "log content");
            AssertZipEntry(zip, @"site\home.aspx", "home content");
            AssertZipEntry(zip, @"site\site.css", "some css");
            AssertZipEntry(zip, @"site\empty-dir\", null);
            AssertZipEntry(zip, @"zero-length-file", null);
        }
开发者ID:GregPerez83,项目名称:kudu,代码行数:31,代码来源:ZipArchiveExtensionFacts.cs


示例18: Restore

        public void Restore(string slnFile)
        {
            using (var resourceStream = _fileSystem.OpenResource("slnRun.Resources.nuget.zip"))
            using (var zipFile = new ZipArchive(resourceStream))
            using (var nugetInputFile = zipFile.GetEntry("nuget.exe").Open())
            {
                var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                _fileSystem.CreateDirectory(tempPath);
                try
                {
                    var targetPath = Path.Combine(tempPath, "nuget.exe");
                    using (var nugetOutputFile = _fileSystem.CreateFile(targetPath))
                        nugetInputFile.CopyTo(nugetOutputFile);

                    var sb = new StringBuilder();
                    var exitCode = _processRunner.Run(targetPath, $"restore \"{slnFile}\"", x => { sb.Append(x); });
                    if (exitCode != 0)
                    {
                        _logger.Error(sb.ToString());
                        throw new SlnRunException("nuget package restore failed.");
                    }
                }
                finally
                {
                    _fileSystem.DeleteDirectory(tempPath);
                }
            }
        }
开发者ID:vetterd,项目名称:slnRun,代码行数:28,代码来源:NuGet.cs


示例19: Archive

        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;
        }
开发者ID:LazyTarget,项目名称:Lux,代码行数:32,代码来源:ZipFileMock.cs


示例20: GetEntries

        IEnumerable<PackageEntry> GetEntries(ZipArchive zipArchive)
        {
            IList<PackageEntry> result = new List<PackageEntry>();

            foreach (ZipArchiveEntry entry in zipArchive.Entries)
            {
                if (entry.FullName.EndsWith("/.rels", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (entry.FullName.EndsWith("[Content_Types].xml", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (entry.FullName.EndsWith(".psmdcp", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                result.Add(new PackageEntry(entry));
            }

            return result;
        }
开发者ID:jinujoseph,项目名称:NuGet.Services.Metadata,代码行数:26,代码来源:PackageEntriesStage.cs



注:本文中的System.IO.Compression.ZipArchive类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Compression.ZipArchiveEntry类代码示例发布时间:2022-05-26
下一篇:
C# Compression.GZipStream类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap