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

C# ZipArchive类代码示例

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

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



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

示例1: UnZip

partial         void UnZip(NSObject sender)
        {
            // Set the desired output directory to place unzipped files
            string theUnzippedFolder = Environment.CurrentDirectory + "/unzipped";

            // Create a new instance of ZipArchiv
            ZipArchive zip = new ZipArchive();

            // You can subscribe to OnError event so you can handle
            // any errors situations
            zip.OnError += (object s, EventArgs e) =>
            {
                string error = s as String;
                Console.WriteLine("Error:" + error);
            };

            // Open the zip file you want to unzip
            zip.UnzipOpenFile(theZipFile);

            // This will return true if succeeded to unzip
            bool unzipped = zip.UnzipFileTo(theUnzippedFolder, true);

            // Dont forget to close the zip file
            zip.UnzipCloseFile();

            if(unzipped)
                new UIAlertView("Info", "Success: " + theUnzippedFolder, null, "Great", null).Show();
            else
                new UIAlertView("Info", "Something went wrong", null, "Ok", null).Show();

            Console.WriteLine(theUnzippedFolder);
        }
开发者ID:amnextking,项目名称:monotouch-bindings,代码行数:32,代码来源:ZipTestViewController.cs


示例2: UnZip

        private async static Task<List<StorageFile>> UnZip()
        {
            var files = new List();

            // open zip
            var zipFile = await Package.Current.InstalledLocation.GetFileAsync("Data.zip");
            using (var zipStream = await zipFile.OpenReadAsync())
            {
                using (var archive = new ZipArchive(zipStream.AsStream()))
                {
                    // iterate through zipped objects
                    foreach (var archiveEntry in archive.Entries)
                    {
                        using (var outStream = archiveEntry.Open())
                        {
                            // unzip file to app's LocalFolder
                            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(archiveEntry.Name);
                            using (var inStream = await file.OpenStreamForWriteAsync())
                            {
                                await outStream.CopyToAsync(inStream);
                            }
                            files.Add(file);
                        }
                    }
                }
            }
        }
开发者ID:KeesPolling,项目名称:Popmail,代码行数:27,代码来源:PrepareMockData.cs


示例3: TestCompressedZip

 public void TestCompressedZip()
 {
     var Zip = new ZipArchive();
     Zip.Load("../../../TestInput/UncompressedZip.zip");
     var ExpectedString = "ffmpeg -i test.pmf -vcodec copy -an test.h264\nffmpeg -i test.pmf -acodec copy -vn test.ac3p";
     var ResultString = Zip["demux.bat"].OpenUncompressedStream().ReadAllContentsAsString(FromStart:false);
     Assert.AreEqual(ExpectedString, ResultString);
 }
开发者ID:soywiz,项目名称:cspspemu,代码行数:8,代码来源:ZipTest.cs


示例4: ZipWritableArchiveEntry

 internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size, DateTime? lastModified)
     : base(archive, null)
 {
     this.Stream = stream;
     this.path = path;
     this.size = size;
     this.lastModified = lastModified;
 }
开发者ID:WimObiwan,项目名称:sharpcompress,代码行数:8,代码来源:ZipWritableArchiveEntry.cs


示例5: TestZip2

 public void TestZip2()
 {
     var Zip = new ZipArchive();
     Zip.Load(ResourceArchive.GetFlash0ZipFileStream());
     foreach (var Entry in Zip)
     {
         Console.Error.WriteLine(Entry);
     }
 }
开发者ID:soywiz,项目名称:cspspemu,代码行数:9,代码来源:ZipTest.cs


示例6: TestUncompressedZip

 public void TestUncompressedZip()
 {
     var Zip = new ZipArchive();
     Zip.Load("../../../TestInput/UncompressedZip.zip");
     foreach (var Entry in Zip)
     {
         Console.Error.WriteLine(Entry);
     }
 }
开发者ID:soywiz,项目名称:cspspemu,代码行数:9,代码来源:ZipTest.cs


示例7: ZipWritableArchiveEntry

 internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size,
                                  DateTime? lastModified, bool closeStream)
     : base(archive, null)
 {
     this.stream = stream;
     this.path = path;
     this.size = size;
     this.LastModifiedTime = lastModified;
     this.closeStream = closeStream;
 }
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:10,代码来源:ZipWritableArchiveEntry.cs


示例8: ZipWithInvalidFileNames_ParsedBasedOnSourceOS

 public static async Task ZipWithInvalidFileNames_ParsedBasedOnSourceOS(string zipName, string fileName)
 {
     using (Stream stream = await StreamHelpers.CreateTempCopyStream(compat(zipName)))
     using (ZipArchive archive = new ZipArchive(stream))
     {
         Assert.Equal(1, archive.Entries.Count);
         ZipArchiveEntry entry = archive.Entries[0];
         Assert.Equal(fileName, entry.Name);
     }
 }
开发者ID:ChuangYang,项目名称:corefx,代码行数:10,代码来源:zip_ManualAndCompatibilityTests.cs


示例9: EmptyEntryTest

        public static void EmptyEntryTest(ZipArchiveMode mode)
        {
            string data1 = "test data written to file.";
            string data2 = "more test data written to file.";
            DateTimeOffset lastWrite = new DateTimeOffset(1992, 4, 5, 12, 00, 30, new TimeSpan(-5, 0, 0));

            var baseline = new LocalMemoryStream();
            using (ZipArchive archive = new ZipArchive(baseline, mode))
            {
                AddEntry(archive, "data1.txt", data1, lastWrite);

                ZipArchiveEntry e = archive.CreateEntry("empty.txt");
                e.LastWriteTime = lastWrite;
                using (Stream s = e.Open()) { }

                AddEntry(archive, "data2.txt", data2, lastWrite);
            }

            var test = new LocalMemoryStream();
            using (ZipArchive archive = new ZipArchive(test, mode))
            {
                AddEntry(archive, "data1.txt", data1, lastWrite);

                ZipArchiveEntry e = archive.CreateEntry("empty.txt");
                e.LastWriteTime = lastWrite;

                AddEntry(archive, "data2.txt", data2, lastWrite);
            }
            //compare
            Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match");

            //second test, this time empty file at end
            baseline = baseline.Clone();
            using (ZipArchive archive = new ZipArchive(baseline, mode))
            {
                AddEntry(archive, "data1.txt", data1, lastWrite);

                ZipArchiveEntry e = archive.CreateEntry("empty.txt");
                e.LastWriteTime = lastWrite;
                using (Stream s = e.Open()) { }
            }

            test = test.Clone();
            using (ZipArchive archive = new ZipArchive(test, mode))
            {
                AddEntry(archive, "data1.txt", data1, lastWrite);

                ZipArchiveEntry e = archive.CreateEntry("empty.txt");
                e.LastWriteTime = lastWrite;
            }
            //compare
            Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match after update");
        }
开发者ID:dotnet,项目名称:corefx,代码行数:53,代码来源:zip_UpdateTests.cs


示例10: ReadStreamOps

 public static async Task ReadStreamOps()
 {
     using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipArchiveMode.Read))
     {
         foreach (ZipArchiveEntry e in archive.Entries)
         {
             using (Stream s = e.Open())
             {
                 Assert.True(s.CanRead, "Can read to read archive");
                 Assert.False(s.CanWrite, "Can't write to read archive");
                 Assert.False(s.CanSeek, "Can't seek on archive");
                 Assert.Equal(ZipTest.LengthOfUnseekableStream(s), e.Length); //"Length is not correct on unseekable stream"
             }
         }
     }
 }
开发者ID:jmhardison,项目名称:corefx,代码行数:16,代码来源:zip_ReadTests.cs


示例11: Compress

        /// <summary>
        /// Compresses an array of bytes.
        /// </summary>
        /// <param name="bytes">The input bytes.</param>
        /// <returns>Returns the compressed bytes.</returns>
        /// <exception cref="System.ArgumentNullException">bytes</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="bytes" /> parameter is null.</exception>
        public static byte[] Compress(byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException("bytes");

            using (var inputStream = new MemoryStream(bytes))
            using (var outputStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(outputStream, ZipArchiveMode.Create, false, null))
                using (ZipArchiveEntry entry = archive.CreateEntry(DataEntryName))
                using (Stream entryStream = entry.Open())
                {
                    inputStream.CopyTo(entryStream);
                }
                return outputStream.ToArray();
            }
        }
开发者ID:mparsin,项目名称:Elements,代码行数:24,代码来源:CompressionUtils.cs


示例12: UpdateReadTwice

 public static async Task UpdateReadTwice()
 {
     using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(zfile("small.zip")), ZipArchiveMode.Update))
     {
         ZipArchiveEntry entry = archive.Entries[0];
         string contents1, contents2;
         using (StreamReader s = new StreamReader(entry.Open()))
         {
             contents1 = s.ReadToEnd();
         }
         using (StreamReader s = new StreamReader(entry.Open()))
         {
             contents2 = s.ReadToEnd();
         }
         Assert.Equal(contents1, contents2);
     }
 }
开发者ID:dotnet,项目名称:corefx,代码行数:17,代码来源:zip_UpdateTests.cs


示例13: WriteFilesRecursiveToZip

        private static void WriteFilesRecursiveToZip(ZipArchive archive, IStorage storage, string basePath)
        {
            string searchPattern = basePath;
            string[] fileNames = storage.GetFileNames(searchPattern);

            foreach (string fileName in fileNames)
            {
                Stream fileStream = storage.OpenFile(basePath + "/" + fileName, StorageFileMode.Open,
                                                     StorageFileAccess.Read);
                archive.AddEntry(fileName, fileStream);
            }

            string[] directrryNames = storage.GetDirectoryNames(searchPattern);
            foreach (string directoryName in directrryNames)
            {
                WriteFilesRecursiveToZip(archive, storage, basePath + "/" + directoryName);
            }
        }
开发者ID:kernelhunter92,项目名称:CatrobatForWindows,代码行数:18,代码来源:CatrobatZip.cs


示例14: ButtonOpenClick

        private void ButtonOpenClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Zip File | *.zip";
            bool? dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
#if WPF
                Stream stream = dialog.OpenFile();
#else
                Stream stream = dialog.File.OpenRead();
#endif
                using (ZipArchive zipArchive = new ZipArchive(stream))
                {
                    OpenedFileList.ItemsSource = zipArchive.Entries;
                }
            }
        }
开发者ID:netintellect,项目名称:PluralsightSpaJumpStartFinal,代码行数:19,代码来源:Example.xaml.cs


示例15: CreateZip

        void CreateZip()
        {
            Console.WriteLine("creating zip file");

            // Needed contents at ZipPath:
            // Files\Application\ --> All contents requied for Programm Files (x86)\Sharpkit\
            // Files\NET\ --> the content of FrameworkDir\SharpKit
            // Files\NET_Unix\ --> only the modified files for unix. At this time, it will contain only the file SharpKit.Build.targets.
            // Files\Templates\ --> contains 'SharpKit Web Application.zip' and 'SharpKit 5 Web Application.zip'

            // Just copy the needed above files to @SourceFilesDir() and run this code.
            // @SourceFilesDir must be the parent directory of Files\

            using (var zip = new ZipArchive(ZipPath) { AddFileCallback = t => Console.WriteLine(t) })
            {
                zip.BeginUpdate();
                zip.AddDirectory(SourceFilesDir);
                zip.EndUpdate();
            }
        }
开发者ID:benbon,项目名称:SharpKit,代码行数:20,代码来源:SetupBuilder.cs


示例16: Uncompress

        /// <summary>
        /// Decompresses an array of bytes.
        /// </summary>
        /// <param name="bytes">The compressed bytes.</param>
        /// <returns>Returns the uncompressed bytes.</returns>
        /// <exception cref="System.ArgumentNullException">bytes</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="bytes" /> parameter is null.</exception>
        public static byte[] Uncompress(byte[] bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException("bytes");

            using (var inputStream = new MemoryStream(bytes))
            {
                using (var zipPackage = new ZipArchive(inputStream, ZipArchiveMode.Read, true, null))
                {
                    using (var outputStream = new MemoryStream())
                    {
                        var entry = zipPackage.Entries.FirstOrDefault(e => e.Name == DataEntryName);

                        if (entry != null)
                            entry.Open().CopyTo(outputStream);

                        return outputStream.ToArray();
                    }
                }
            }
        }
开发者ID:mparsin,项目名称:Elements,代码行数:28,代码来源:CompressionUtils.cs


示例17: ButtonSaveClick

 private void ButtonSaveClick(object sender, RoutedEventArgs e)
 {
     SaveFileDialog dialog = new SaveFileDialog();
     dialog.Filter = "Zip File | *.zip";
     bool? dialogResult = dialog.ShowDialog();
     if (dialogResult == true)
     {
         using (ZipArchive zipArchive = new ZipArchive(dialog.OpenFile(), ZipArchiveMode.Create, false, null))
         {
             IEnumerable<DataItem> selectedFiles = items.Where(CheckIsFileSelected);
             foreach (DataItem file in selectedFiles)
             {
                 MemoryStream stream = CreateNewFile(file);
                 using (ZipArchiveEntry archiveEntry = zipArchive.CreateEntry(file.FileName))
                 {
                     Stream entryStream = archiveEntry.Open();
                     stream.CopyTo(entryStream);
                 }
             }
         }
     }
 }
开发者ID:netintellect,项目名称:PluralsightSpaJumpStartFinal,代码行数:22,代码来源:Example.xaml.cs


示例18: CreateModeInvalidOperations

        public static void CreateModeInvalidOperations()
        {
            MemoryStream ms = new MemoryStream();
            ZipArchive z = new ZipArchive(ms, ZipArchiveMode.Create);
            Assert.Throws<NotSupportedException>(() => { var x = z.Entries; }); //"Entries not applicable on Create"
            Assert.Throws<NotSupportedException>(() => z.GetEntry("dirka")); //"GetEntry not applicable on Create"

            ZipArchiveEntry e = z.CreateEntry("hey");
            Assert.Throws<NotSupportedException>(() => e.Delete()); //"Can't delete new entry"

            Stream s = e.Open();
            Assert.Throws<NotSupportedException>(() => s.ReadByte()); //"Can't read on new entry"
            Assert.Throws<NotSupportedException>(() => s.Seek(0, SeekOrigin.Begin)); //"Can't seek on new entry"
            Assert.Throws<NotSupportedException>(() => s.Position = 0); //"Can't set position on new entry"
            Assert.Throws<NotSupportedException>(() => { var x = s.Length; }); //"Can't get length on new entry"

            Assert.Throws<IOException>(() => e.LastWriteTime = new DateTimeOffset()); //"Can't get LastWriteTime on new entry"
            Assert.Throws<InvalidOperationException>(() => { var x = e.Length; }); //"Can't get length on new entry"
            Assert.Throws<InvalidOperationException>(() => { var x = e.CompressedLength; }); //"can't get CompressedLength on new entry"

            Assert.Throws<IOException>(() => z.CreateEntry("bad"));
            s.Dispose();

            Assert.Throws<ObjectDisposedException>(() => s.WriteByte(25)); //"Can't write to disposed entry"

            Assert.Throws<IOException>(() => e.Open());
            Assert.Throws<IOException>(() => e.LastWriteTime = new DateTimeOffset());
            Assert.Throws<InvalidOperationException>(() => { var x = e.Length; });
            Assert.Throws<InvalidOperationException>(() => { var x = e.CompressedLength; });

            ZipArchiveEntry e1 = z.CreateEntry("e1");
            ZipArchiveEntry e2 = z.CreateEntry("e2");

            Assert.Throws<IOException>(() => e1.Open()); //"Can't open previous entry after new entry created"

            z.Dispose();

            Assert.Throws<ObjectDisposedException>(() => z.CreateEntry("dirka")); //"Can't create after dispose"
        }
开发者ID:SGuyGe,项目名称:corefx,代码行数:39,代码来源:zip_CreateTests.cs


示例19: Extract

 public static void Extract(Stream zipStream, string targetDirectory)
 {
     var zipArchive = new ZipArchive();
     zipArchive.ReadFrom(zipStream);
     foreach (var entry in zipArchive.Entries)
     {
         if (entry is ZipFileEntry)
         {
             var fileEntry = entry as ZipFileEntry;
             string absoluteFilePath = Path.Combine(targetDirectory, fileEntry.FileName);
             string directoryName = Path.GetDirectoryName(absoluteFilePath);
             if (!Directory.Exists(directoryName))
             {
                 Directory.CreateDirectory(directoryName);
             }
             if (File.Exists(absoluteFilePath))
             {
                 File.Delete(absoluteFilePath);
             }
             var fileStream = new FileStream(absoluteFilePath, FileMode.CreateNew);
             if (fileEntry.Data != null && fileEntry.Data.Length != 0)
             {
                 WriteStream(fileEntry.Data, fileStream);
             }
             fileStream.Close();
         }
         else if (entry is ZipDirectoryEntry)
         {
             var directoryEntry = entry as ZipDirectoryEntry;
             string directoryName = Path.Combine(targetDirectory, directoryEntry.DirectoryName);
             if (!Directory.Exists(directoryName))
             {
                 Directory.CreateDirectory(directoryName);
             }
         }
     }
 }
开发者ID:GraemeF,项目名称:openwrap-bootstrap,代码行数:37,代码来源:ZipArchive.cs


示例20: UpdateModeInvalidOperations

        public static async Task UpdateModeInvalidOperations()
        {
            using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(zfile("normal.zip")))
            {
                ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, true);

                ZipArchiveEntry edeleted = target.GetEntry("first.txt");

                Stream s = edeleted.Open();
                //invalid ops while entry open
                Assert.Throws<IOException>(() => edeleted.Open());
                Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
                Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });
                Assert.Throws<IOException>(() => edeleted.Delete());
                s.Dispose();

                //invalid ops on stream after entry closed
                Assert.Throws<ObjectDisposedException>(() => s.ReadByte());

                Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; });
                Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; });

                edeleted.Delete();
                //invalid ops while entry deleted
                Assert.Throws<InvalidOperationException>(() => edeleted.Open());
                Assert.Throws<InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); });

                ZipArchiveEntry e = target.GetEntry("notempty/second.txt");

                target.Dispose();

                Assert.Throws<ObjectDisposedException>(() => { var x = target.Entries; });
                Assert.Throws<ObjectDisposedException>(() => target.CreateEntry("dirka"));
                Assert.Throws<ObjectDisposedException>(() => e.Open());
                Assert.Throws<ObjectDisposedException>(() => e.Delete());
                Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); });
            }
        }
开发者ID:dotnet,项目名称:corefx,代码行数:38,代码来源:zip_UpdateTests.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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