Ejemplo n.º 1
0
        public async Task<ZipArchive> GetUserArchiveAsync(ZipArchiveMode mode)
        {
            var zipFile = await this._rootFolder.CreateFileAsync($"{this._sessionStateService.DropboxUserId}.zip", CreationCollisionOption.OpenIfExists);
            IRandomAccessStream stream = await zipFile.OpenAsync(mode == ZipArchiveMode.Read ? FileAccessMode.Read : FileAccessMode.ReadWrite, StorageOpenOptions.None);

            return new ZipArchive(stream.AsStream(), mode, false, Encoding.UTF8);
        }
Ejemplo n.º 2
0
        public virtual IZipArchive ZipArchiveFromDocument( byte[] document, ZipArchiveMode mode = ZipArchiveMode.Read )
        {
            var stream = new MemoryStream( document );

            var archive = new ZipWrapper( stream, mode, true );

            return archive;
        }
Ejemplo n.º 3
0
 //public ZipArchive(string file, FileMode fileMode)
 public ZipArchive(FileStream fs, ZipArchiveMode mode, Encoding entryNameEncoding = null)
 {
     //_file = file;
     //Open(fileMode);
     if (entryNameEncoding == null)
         entryNameEncoding = Encoding.UTF8;
     _zipArchive = new System.IO.Compression.ZipArchive(fs, mode, false, entryNameEncoding);
 }
Ejemplo n.º 4
0
		public ZipArchive (Stream stream, ZipArchiveMode mode)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");

			this.stream = stream;
			this.mode = mode;
			CreateZip(stream, mode);
		}
Ejemplo n.º 5
0
		public ZipArchive (Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");

			this.stream = stream;
			mode = ZipArchiveMode.Read;
			CreateZip(mode);
		}
Ejemplo n.º 6
0
 public ZipWrapper(Stream stream, ZipArchiveMode mode, bool leaveOpen)
 {
     _entries = new List<IZipEntry>();
     _zip = new ZipArchive(stream, mode, leaveOpen);
     foreach (var zipEntry in _zip.Entries)
     {
         _entries.Add(new ZipEntry(zipEntry));
     }
 }
Ejemplo n.º 7
0
		public ZipArchive (Stream stream, ZipArchiveMode mode, bool leaveOpen)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");

			this.stream = stream;
			this.mode = mode;
			leaveStreamOpen = leaveOpen;
			CreateZip(stream, mode);
		}
Ejemplo n.º 8
0
		public ZipArchive (Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding entryNameEncoding)
		{
			if (stream == null)
				throw new ArgumentNullException("stream");

			this.stream = stream;
			this.mode = mode;
			leaveStreamOpen = leaveOpen;
			this.entryNameEncoding = entryNameEncoding;
			CreateZip(mode);
		}
Ejemplo n.º 9
0
        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");
        }
Ejemplo n.º 10
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="ZipFilePath"></param>
		/// <param name="Mode"></param>
		public ZipFileSystem(String ZipFilePath, ZipArchiveMode Mode)
		{
			this.ZipFilePath = ZipFilePath;
			this.Mode = Mode;
			switch (Mode)
			{
				case ZipArchiveMode.Create: this.ZipStream = File.Open(ZipFilePath, FileMode.Create, FileAccess.Write, FileShare.Read); break;
				case ZipArchiveMode.Read: this.ZipStream = File.OpenRead(ZipFilePath); break;
				case ZipArchiveMode.Update: this.ZipStream = File.Open(ZipFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); break;
				default: throw(new NotImplementedException());
			}
			this.ZipArchive = new ZipArchive(this.ZipStream, (System.IO.Compression.ZipArchiveMode)Mode);
		}
Ejemplo n.º 11
0
        /// <summary>
        /// Internal constructor that is called by the Open(Stream) static methods.
        /// </summary>
        /// <param name="s"></param>
        /// <param name="packageFileMode"></param>
        /// <param name="packageFileAccess"></param>
        internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
            : base(packageFileAccess)
        {
            ZipArchive?       zipArchive = null;
            ContentTypeHelper?contentTypeHelper;

            _packageFileMode   = packageFileMode;
            _packageFileAccess = packageFileAccess;

            try
            {
                if (s.CanSeek)
                {
                    switch (packageFileMode)
                    {
                    case FileMode.Open:
                        if (s.Length == 0)
                        {
                            throw new FileFormatException(SR.ZipZeroSizeFileIsNotValidArchive);
                        }
                        break;

                    case FileMode.CreateNew:
                        if (s.Length != 0)
                        {
                            throw new IOException(SR.CreateNewOnNonEmptyStream);
                        }
                        break;

                    case FileMode.Create:
                        if (s.Length != 0)
                        {
                            s.SetLength(0);     // Discard existing data
                        }
                        break;
                    }
                }

                ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
                if (packageFileAccess == FileAccess.Read)
                {
                    zipArchiveMode = ZipArchiveMode.Read;
                }
                else if (packageFileAccess == FileAccess.Write)
                {
                    zipArchiveMode = ZipArchiveMode.Create;
                }
                else if (packageFileAccess == FileAccess.ReadWrite)
                {
                    zipArchiveMode = ZipArchiveMode.Update;
                }

                zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);

                _zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
                contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
            }
            catch (InvalidDataException)
            {
                throw new FileFormatException(SR.FileContainsCorruptedData);
            }
            catch
            {
                if (zipArchive != null)
                {
                    zipArchive.Dispose();
                }

                throw;
            }

            _containerStream            = s;
            _shouldCloseContainerStream = false;
            _zipArchive        = zipArchive;
            _contentTypeHelper = contentTypeHelper;
        }
Ejemplo n.º 12
0
 public static ZipArchive CreateZipArchive(Stream stream, ZipArchiveMode mode)
 {
     return(new ZipArchive(stream, mode, true, Encoding.UTF8));
 }
Ejemplo n.º 13
0
		private void CreateZip(ZipArchiveMode mode)
		{
			try {
				if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update)
					throw new ArgumentOutOfRangeException("mode");

				// If the mode parameter is set to Read, the stream must support reading.
				if (mode == ZipArchiveMode.Read && !stream.CanRead)
					throw new ArgumentException("Stream must support reading for Read archive mode");

				// If the mode parameter is set to Create, the stream must support writing.
				if (mode == ZipArchiveMode.Create && !stream.CanWrite)
					throw new ArgumentException("Stream must support writing for Create archive mode");

				// If the mode parameter is set to Update, the stream must support reading, writing, and seeking.
				if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek))
					throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode");

				// If the stream is not seekable, then buffer it into memory (same behavior as .NET). 
				if (mode == ZipArchiveMode.Read && !stream.CanSeek)
				{
					var memoryStream = new MemoryStream();
					stream.CopyTo(memoryStream);

					if (!leaveStreamOpen)
						stream.Dispose();

					this.stream = memoryStream;
				}

				try {
					zipFile = mode != ZipArchiveMode.Create && stream.Length != 0
						? SharpCompress.Archive.Zip.ZipArchive.Open(stream)
						: SharpCompress.Archive.Zip.ZipArchive.Create();
				} catch (Exception e) {
					throw new InvalidDataException("The contents of the stream are not in the zip archive format.", e);
				}

				entries = new List<ZipArchiveEntry>();
				if (Mode != ZipArchiveMode.Create) {
					foreach (var entry in zipFile.Entries) {
						var zipEntry = new ZipArchiveEntry(this, entry);
						entries.Add(zipEntry);
					}
				}
			}
			catch {
				if (!leaveStreamOpen)
					stream.Dispose();
				throw;
			}
		}
Ejemplo n.º 14
0
 /// <summary>
 /// Opens a zip archive at the specified path and in the specified mode.
 /// </summary>
 /// <param name="archiveFileName">The path to the archive to open, specified as a relative or absolute path. A relative path is interpreted as relative to the current working directory.</param>
 /// <param name="mode">One of the enumeration values that specifies the actions which are allowed on the entries in the opened archive.</param>
 /// <returns>The opened zip archive.</returns>
 /// <exception cref="T:System.ArgumentException"><paramref name="archiveFileName"/> is <see cref="F:System.String.Empty"/>, contains only white space, or contains at least one invalid character.</exception>
 /// <exception cref="T:System.ArgumentNullException"><paramref name="archiveFileName"/> is null.</exception>
 /// <exception cref="T:System.IO.PathTooLongException">In <paramref name="archiveFileName"/>, the specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must not exceed 248 characters, and file names must not exceed 260 characters.</exception>
 /// <exception cref="T:System.IO.DirectoryNotFoundException"><paramref name="archiveFileName"/> is invalid or does not exist (for example, it is on an unmapped drive).</exception>
 /// <exception cref="T:System.IO.IOException"><paramref name="archiveFileName"/> could not be opened.-or-<paramref name="mode"/> is set to <see cref="ZipArchiveMode.Create" />, but the file specified in <paramref name="archiveFileName"/> already exists.</exception>
 /// <exception cref="T:System.UnauthorizedAccessException"><paramref name="archiveFileName"/> specifies a directory.-or-The caller does not have the required permission to access the file specified in <paramref name="archiveFileName"/>.</exception>
 /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="mode"/> specifies an invalid value.</exception>
 /// <exception cref="T:System.IO.FileNotFoundException"><paramref name="mode"/> is set to <see cref="ZipArchiveMode.Read" />, but the file specified in <paramref name="archiveFileName"/> is not found.</exception>
 /// <exception cref="T:System.NotSupportedException"><paramref name="archiveFileName"/> contains an invalid format.</exception>
 /// <exception cref="T:System.IO.InvalidDataException"><paramref name="archiveFileName"/> could not be interpreted as a zip archive.-or-<paramref name="mode"/> is <see cref="ZipArchiveMode.Update" />, but an entry is missing or corrupt and cannot be read.-or-<paramref name="mode"/> is <see cref="ZipArchiveMode.Update" />, but an entry is too large to fit into memory.</exception>
 public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode)
 {
     return(ZipFile.Open(archiveFileName, mode, null));
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open.
 /// </summary>
 /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
 /// <exception cref="ArgumentNullException">The stream is null.</exception>
 /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
 /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
 /// <param name="stream">The input or output stream.</param>
 /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
 /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param>
 public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(stream, mode, leaveOpen, entryNameEncoding : null)
 {
 }
Ejemplo n.º 16
0
		public ZipArchive (Stream stream, ZipArchiveMode mode)
			: this (stream)
		{
		}
Ejemplo n.º 17
0
 public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding);
Ejemplo n.º 18
0
        private void Init(Stream stream, ZipArchiveMode mode, bool leaveOpen)
        {
            try
            {
                this.originalStream = (Stream)null;
                switch (mode)
                {
                case ZipArchiveMode.Create:
                    if (!stream.CanWrite || !stream.CanSeek)
                    {
                        throw new ArgumentException("Stream must support writing and seeking.");
                    }
                    stream.SetLength(0L);
                    break;

                case ZipArchiveMode.Read:
                    if (!stream.CanRead)
                    {
                        throw new ArgumentException("Stream must support reading.");
                    }
                    if (!stream.CanSeek)
                    {
                        this.originalStream = stream;
                        stream = PlatformSettings.Manager.CreateTemporaryStream();
                        ZipFile.CopyStreamTo(this.originalStream, stream);
                        stream.Seek(0L, SeekOrigin.Begin);
                        break;
                    }
                    break;

                case ZipArchiveMode.Update:
                    if (stream.CanRead && stream.CanSeek)
                    {
                        this.originalStream = stream;
                        stream = PlatformSettings.Manager.CreateTemporaryStream();
                        stream.Seek(0L, SeekOrigin.Begin);
                        if (stream.CanWrite)
                        {
                            break;
                        }
                    }
                    throw new ArgumentException("Stream must support reading, writing and seeking.");

                default:
                    throw new ArgumentOutOfRangeException(nameof(mode));
                }
                this.archiveMode   = mode;
                this.workingStream = stream;
                switch (mode)
                {
                case ZipArchiveMode.Read:
                    this.archiveWriter = (BinaryWriter)null;
                    this.archiveReader = new BinaryReader(this.workingStream);
                    break;

                case ZipArchiveMode.Update:
                    this.archiveReader = new BinaryReader(this.originalStream);
                    this.archiveWriter = new BinaryWriter(this.workingStream);
                    break;

                default:
                    this.archiveReader = (BinaryReader)null;
                    this.archiveWriter = new BinaryWriter(this.workingStream);
                    break;
                }
                this.centralDirectoryRead = false;
                this.leaveStreamOpen      = leaveOpen;
                switch (mode)
                {
                case ZipArchiveMode.Create:
                    this.centralDirectoryRead = true;
                    break;

                case ZipArchiveMode.Read:
                    this.ReadEndOfCentralDirectory();
                    break;

                case ZipArchiveMode.Update:
                    if (this.Reader.BaseStream.Length != 0L)
                    {
                        this.ReadEndOfCentralDirectory();
                        this.EnsureCentralDirectoryRead();
                        using (IEnumerator <ZipArchiveEntry> enumerator = this.Entries.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                ZipArchiveEntry current = enumerator.Current;
                                string          message = (string)null;
                                if (!current.CheckIntegrity(out message))
                                {
                                    throw new InvalidDataException(message);
                                }
                            }
                            break;
                        }
                    }
                    else
                    {
                        this.centralDirectoryRead = true;
                        break;
                    }
                }
            }
            catch
            {
                if (this.originalStream != null)
                {
                    PlatformSettings.Manager.DeleteTemporaryStream(this.workingStream);
                }
                throw;
            }
        }
Ejemplo n.º 19
0
        public static void IsZipSameAsDir(Stream archiveFile, String directory, ZipArchiveMode mode, Boolean dontRequireExplicit, Boolean dontCheckTimes)
        {
            int count = 0;

            using (ZipArchive archive = new ZipArchive(archiveFile, mode))
            {
                var allFilesInDir = FileData.InPath(directory);
                foreach (var file in allFilesInDir)
                {
                    count++;
                    String entryName = file.FullName;
                    if (file.IsFolder)
                    {
                        entryName += Path.DirectorySeparatorChar;
                    }

                    ZipArchiveEntry entry = archive.GetEntry(entryName);
                    if (entry == null)
                    {
                        entryName = FlipSlashes(entryName);
                        entry     = archive.GetEntry(entryName);
                    }

                    if (file.IsFile)
                    {
                        try
                        {
                            Assert.NotNull(entry);
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("File Entry {0} in directory but not archive: {1}", entryName, file.FullName);
                            throw;
                        }

                        Int64 givenLength = entry.Length;

                        var buffer = new byte[entry.Length];
                        using (Stream entrystream = entry.Open())
                        {
                            entrystream.Read(buffer, 0, buffer.Length);
                            String crc = CRC.CalculateCRC(buffer);
                            Assert.Equal(file.Length, givenLength);
                            Assert.Equal(file.CRC, crc);
                        }

                        if (!dontCheckTimes)
                        {
                            Double offBy = (file.LastModifiedDate - entry.LastWriteTime.DateTime).TotalSeconds;
                            Assert.True(
                                (offBy >= -2 && offBy <= 2) ||
                                // Temporary adjustment for active issue 1326
                                ((offBy >= 3598 && offBy <= 3602)),
                                String.Format("{0}, {1}, {2}", file.LastModifiedDate.ToString(), entry.LastWriteTime.DateTime.ToString(), file.FullName));
                        }

                        Assert.Equal(file.Name, entry.Name);
                        Assert.Equal(entryName, entry.FullName);
                        Assert.Equal(entryName, entry.ToString());
                        Assert.Equal(archive, entry.Archive);
                    }
                    else if (file.IsFolder)
                    {
                        if (entry == null) //entry not found
                        {
                            string  entryNameOtherSlash = FlipSlashes(entryName);
                            Boolean isEmtpy             = !allFilesInDir.Any(
                                f => f.IsFile &&
                                (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) ||
                                 f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase)));
                            if ((!dontRequireExplicit || isEmtpy) && !entryName.Contains("emptydir"))
                            {
                                Assert.True(false, String.Format("Folder Entry {0} in directory but not archive: {1}", entryName, directory));
                            }

                            if ((dontRequireExplicit && !isEmtpy) || entryName.Contains("emptydir"))
                            {
                                count--; //discount this entry
                            }
                        }
                        else
                        {
                            using (Stream es = entry.Open())
                            {
                                try
                                {
                                    Assert.True(es.Length == 0, "Length should be 0");
                                }
                                catch (NotSupportedException)
                                {
                                    try
                                    {
                                        Assert.Equal(-1, es.ReadByte());
                                    }
                                    catch (Exception)
                                    {
                                        Console.WriteLine("Didn't return EOF");
                                        throw;
                                    }
                                }
                            }
                        }
                    }
                }

                Assert.Equal(count, archive.Entries.Count);
            }
        }
Ejemplo n.º 20
0
 public static ZipArchive Open(
     string archiveFileName, ZipArchiveMode mode,
     Encoding entryNameEncoding)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 21
0
 /// <summary>Opens a zip archive at the specified path and in the specified mode.</summary>
 /// <param name="this">
 ///     The path to the archive to open, specified as a relative or absolute
 ///     path. A relative path is interpreted as relative to the current working directory.
 /// </param>
 /// <param name="mode">
 ///     One of the enumeration values that specifies the actions that are allowed
 ///     on the entries in the opened archive.
 /// </param>
 /// <param name="entryNameEncoding">
 ///     The encoding to use when reading or writing entry names in
 ///     this archive. Specify a value for this parameter only when an encoding is required for
 ///     interoperability with zip archive tools and libraries that do not support UTF-8 encoding for
 ///     entry names.
 /// </param>
 /// <returns>A ZipArchive.</returns>
 public static ZipArchive OpenZipFile(this FileInfo @this, ZipArchiveMode mode, Encoding entryNameEncoding)
 {
     return(ZipFile.Open(@this.FullName, mode, entryNameEncoding));
 }
Ejemplo n.º 22
0
 /// <summary>Opens a zip archive at the specified path and in the specified mode.</summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="mode">
 ///     One of the enumeration values that specifies the actions that are allowed
 ///     on the entries in the opened archive.
 /// </param>
 /// <returns>A ZipArchive.</returns>
 public static ZipArchive OpenZipFile(this FileInfo @this, ZipArchiveMode mode)
 {
     return(ZipFile.Open(@this.FullName, mode));
 }
 /// <summary>Opens a zip archive at the specified path and in the specified mode.</summary>
 /// <param name="this">
 ///     The path to the archive to open, specified as a relative or absolute
 ///     path. A relative path is interpreted as relative to the current working directory.
 /// </param>
 /// <param name="mode">
 ///     One of the enumeration values that specifies the actions that are allowed
 ///     on the entries in the opened archive.
 /// </param>
 /// <param name="entryNameEncoding">
 ///     The encoding to use when reading or writing entry names in
 ///     this archive. Specify a value for this parameter only when an encoding is required for
 ///     interoperability with zip archive tools and libraries that do not support UTF-8 encoding for
 ///     entry names.
 /// </param>
 /// <returns>A ZipArchive.</returns>
 public static ZipArchive OpenZipFile(this FileInfo @this, ZipArchiveMode mode, Encoding entryNameEncoding)
 {
     return ZipFile.Open(@this.FullName, mode, entryNameEncoding);
 }
Ejemplo n.º 24
0
        private void Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen)
        {
            Stream extraTempStream = null;

            try
            {
                _backingStream = null;

                //check stream against mode
                switch (mode)
                {
                    case ZipArchiveMode.Create:
                        if (!stream.CanWrite)
                            throw new ArgumentException(SR.CreateModeCapabilities);
                        break;
                    case ZipArchiveMode.Read:
                        if (!stream.CanRead)
                            throw new ArgumentException(SR.ReadModeCapabilities);
                        if (!stream.CanSeek)
                        {
                            _backingStream = stream;
                            extraTempStream = stream = new MemoryStream();
                            _backingStream.CopyTo(stream);
                            stream.Seek(0, SeekOrigin.Begin);
                        }
                        break;
                    case ZipArchiveMode.Update:
                        if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)
                            throw new ArgumentException(SR.UpdateModeCapabilities);
                        break;
                    default:
                        //still have to throw this, because stream constructor doesn't do mode argument checks
                        throw new ArgumentOutOfRangeException("mode");
                }

                _mode = mode;
                _archiveStream = stream;
                _archiveStreamOwner = null;
                if (mode == ZipArchiveMode.Create)
                    _archiveReader = null;
                else
                    _archiveReader = new BinaryReader(stream);
                _entries = new List<ZipArchiveEntry>();
                _entriesCollection = new ReadOnlyCollection<ZipArchiveEntry>(_entries);
                _entriesDictionary = new Dictionary<String, ZipArchiveEntry>();
                _readEntries = false;
                _leaveOpen = leaveOpen;
                _centralDirectoryStart = 0; //invalid until ReadCentralDirectory
                _isDisposed = false;
                _numberOfThisDisk = 0; //invalid until ReadCentralDirectory
                _archiveComment = null;

                switch (mode)
                {
                    case ZipArchiveMode.Create:
                        _readEntries = true;
                        break;
                    case ZipArchiveMode.Read:
                        ReadEndOfCentralDirectory();
                        break;
                    case ZipArchiveMode.Update:
                    default:
                        Debug.Assert(mode == ZipArchiveMode.Update);
                        if (_archiveStream.Length == 0)
                        {
                            _readEntries = true;
                        }
                        else
                        {
                            ReadEndOfCentralDirectory();
                            EnsureCentralDirectoryRead();
                            foreach (ZipArchiveEntry entry in _entries)
                            {
                                entry.ThrowIfNotOpenable(false, true);
                            }
                        }
                        break;
                }
            }
            catch
            {
                if (extraTempStream != null)
                    extraTempStream.Dispose();

                throw;
            }
        }
Ejemplo n.º 25
0
 private static ZipArchive CreateZipArchive(Stream stream, ZipArchiveMode model)
 {
     return(new ZipArchive(stream, model, true));
 }
Ejemplo n.º 26
0
 public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode);
Ejemplo n.º 27
0
		public ZipArchive (Stream stream, ZipArchiveMode mode,
		                   bool leaveOpen, Encoding entryNameEncoding)
			: this (stream, mode, leaveOpen)
		{
		}
Ejemplo n.º 28
0
        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))
            {
                if (mode == ZipArchiveMode.Create)
                {
                    AddEntry(archive, "data1.txt", data1, lastWrite);

                    ZipArchiveEntry e = archive.CreateEntry("empty.txt");
                    e.LastWriteTime = lastWrite;
                    using (Stream s = e.Open()) { }
                }
                else
                {
                    Assert.Throws <InvalidOperationException>(() => AddEntry(archive, "data1.txt", data1, lastWrite));

                    Assert.Throws <InvalidOperationException>(() => archive.CreateEntry("empty.txt"));
                }
            }

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

                    ZipArchiveEntry e = archive.CreateEntry("empty.txt");
                    e.LastWriteTime = lastWrite;
                }
                else
                {
                    Assert.Throws <InvalidOperationException>(() => AddEntry(archive, "data1.txt", data1, lastWrite));

                    Assert.Throws <InvalidOperationException>(() => archive.CreateEntry("empty.txt"));
                }
            }
            //compare
            Assert.True(ArraysEqual(baseline.ToArray(), test.ToArray()), "Arrays didn't match after update");
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open.
 /// </summary>
 /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
 /// <exception cref="ArgumentNullException">The stream is null.</exception>
 /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
 /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
 /// <param name="stream">The input or output stream.</param>
 /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
 /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param>
 public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) : this(stream, mode, leaveOpen, entryNameEncoding: null) { }
Ejemplo n.º 30
0
 /// <summary>
 /// Creates the package as a ZipArchive.
 /// </summary>
 public async Task <ZipArchive> CreateAsync(ZipArchiveMode mode)
 {
     return(new ZipArchive(await CreateAsStreamAsync(), ZipArchiveMode.Update, leaveOpen: false));
 }
Ejemplo n.º 31
0
        public static ZipPackage Open(Stream stream)
        {
            ZipArchiveMode mode = stream.CanWrite ? ZipArchiveMode.Update : ZipArchiveMode.Read;

            return(new ZipPackage(stream, mode));
        }
 public ZipArchiveSerializerSettingsProvider(ZipArchiveMode mode)
 {
     _mode = mode;
 }
Ejemplo n.º 33
0
 public ZipArchive OpenArchive(string path, ZipArchiveMode mode)
 {
     return ZipFile.Open(path, mode);
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Creates the package as a ZipArchive.
 /// </summary>
 public ZipArchive Create(ZipArchiveMode mode)
 {
     return(new ZipArchive(CreateAsStream(), ZipArchiveMode.Update, leaveOpen: false));
 }
 public ZipArchive(Stream stream, ZipArchiveMode mode);
Ejemplo n.º 36
0
 private XapBuilder CreateFakeInputXap(IFileSystem fileSystem, ZipArchiveMode mode, params string[] assemblies)
 {
     return CreateFakeInputXap(fileSystem, mode, CompressionLevel.Optimal, assemblies);
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Opens a <code>ZipArchive</code> on the specified <code>archiveFileName</code> in the specified <code>ZipArchiveMode</code> mode.
 /// </summary>
 ///
 /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace,
 ///                                     or contains one or more invalid characters as defined by InvalidPathChars.</exception>
 /// <exception cref="ArgumentNullException">path is null.</exception>
 /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length.
 ///                                        For example, on Windows-based platforms, paths must be less than 248 characters,
 ///                                        and file names must be less than 260 characters.</exception>
 /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception>
 /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception>
 /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory.
 ///                                               -OR- The caller does not have the required permission.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><code>mode</code> specified an invalid value.</exception>
 /// <exception cref="FileNotFoundException">The file specified in <code>archiveFileName</code> was not found. </exception>
 /// <exception cref="NotSupportedException"><code>archiveFileName</code> is in an invalid format.</exception>
 /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file.
 ///                                        -OR- <code>mode</code> is <code>Update</code> and an entry is missing from the archive or
 ///                                        is corrupt and cannot be read.
 ///                                        -OR- <code>mode</code> is <code>Update</code> and an entry is too large to fit into memory.</exception>
 ///
 /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on.
 /// The path is permitted to specify relative or absolute path information.
 /// Relative path information is interpreted as relative to the current working directory.</param>
 /// <param name="mode">See the description of the <code>ZipArchiveMode</code> enum.
 /// If <code>Read</code> is specified, the file is opened with <code>System.IO.FileMode.Open</code>, and will throw
 /// a <code>FileNotFoundException</code> if the file does not exist.
 /// If <code>Create</code> is specified, the file is opened with <code>System.IO.FileMode.CreateNew</code>, and will throw
 /// a <code>System.IO.IOException</code> if the file already exists.
 /// If <code>Update</code> is specified, the file is opened with <code>System.IO.FileMode.OpenOrCreate</code>.
 /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created.
 /// If the file exists and is not a Zip file, a <code>ZipArchiveException</code> will be thrown.
 /// If the file exists and is empty or does not exist, a new Zip file will be created.
 /// Note that creating a Zip file with the <code>ZipArchiveMode.Create</code> mode is more efficient when creating a new Zip file.</param>
 public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode) => Open(archiveFileName, mode, entryNameEncoding: null);
Ejemplo n.º 38
0
        private void CreateZip(ZipArchiveMode mode)
        {
            try {
                if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update)
                {
                    throw new ArgumentOutOfRangeException("mode");
                }

                // If the mode parameter is set to Read, the stream must support reading.
                if (mode == ZipArchiveMode.Read && !stream.CanRead)
                {
                    throw new ArgumentException("Stream must support reading for Read archive mode");
                }

                // If the mode parameter is set to Create, the stream must support writing.
                if (mode == ZipArchiveMode.Create && !stream.CanWrite)
                {
                    throw new ArgumentException("Stream must support writing for Create archive mode");
                }

                // If the mode parameter is set to Update, the stream must support reading, writing, and seeking.
                if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek))
                {
                    throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode");
                }

                // If the stream is not seekable, then buffer it into memory (same behavior as .NET).
                if (mode == ZipArchiveMode.Read && !stream.CanSeek)
                {
                    var memoryStream = new MemoryStream();
                    stream.CopyTo(memoryStream);

                    if (!leaveStreamOpen)
                    {
                        stream.Dispose();
                    }

                    this.stream = memoryStream;
                }

                try {
                    zipFile = mode != ZipArchiveMode.Create && stream.Length != 0
                                                ? SharpCompress.Archive.Zip.ZipArchive.Open(stream)
                                                : SharpCompress.Archive.Zip.ZipArchive.Create();
                } catch (Exception e) {
                    throw new InvalidDataException("The contents of the stream are not in the zip archive format.", e);
                }

                entries = new List <ZipArchiveEntry>();
                if (Mode != ZipArchiveMode.Create)
                {
                    foreach (var entry in zipFile.Entries)
                    {
                        var zipEntry = new ZipArchiveEntry(this, entry);
                        entries.Add(zipEntry);
                    }
                }
            }
            catch {
                if (!leaveStreamOpen)
                {
                    stream.Dispose();
                }
                throw;
            }
        }
 public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen);
Ejemplo n.º 40
0
 public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode)
 {
     await IsZipSameAsDirAsync(archiveFile, directory, mode, false, false);
 }
Ejemplo n.º 41
0
        private XapBuilder CreateFakeInputXap(IFileSystem fileSystem, ZipArchiveMode mode, CompressionLevel compressionLevel, params string[] assemblies)
        {
            var builder = new XapBuilder(compressionLevel);

            foreach (string assembly in assemblies)
            {
                builder.AddAssemblyPart(assembly, 10000);
            }

            fileSystem.FileExists("Input.xap").Returns(true);
            fileSystem.OpenArchive("Input.xap", mode).Returns(a => new ZipArchive(builder.Build(), mode, true));

            return builder;
        }
Ejemplo n.º 42
0
        public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode)
        {
            var files = FileData.InPath(directory);

            using (ZipArchive archive = new ZipArchive(archiveStream, mode, true))
            {
                foreach (var i in files)
                {
                    if (i.IsFolder)
                    {
                        string entryName = i.FullName;

                        ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/");
                        e.LastWriteTime = i.LastModifiedDate;
                    }
                }

                foreach (var i in files)
                {
                    if (i.IsFile)
                    {
                        string entryName = i.FullName;

                        var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName));

                        if (installStream != null)
                        {
                            ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/'));
                            e.LastWriteTime = i.LastModifiedDate;
                            using (Stream entryStream = e.Open())
                            {
                                installStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
            }
        }
 /// <summary>Opens a zip archive at the specified path and in the specified mode.</summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="mode">
 ///     One of the enumeration values that specifies the actions that are allowed
 ///     on the entries in the opened archive.
 /// </param>
 /// <returns>A ZipArchive.</returns>
 public static ZipArchive OpenZipFile(this FileInfo @this, ZipArchiveMode mode)
 {
     return ZipFile.Open(@this.FullName, mode);
 }
Ejemplo n.º 44
0
 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]  // See comment in the body.
 public static ZipArchive Open(String archiveFileName, ZipArchiveMode mode)
 {
     return(Open(archiveFileName, mode, entryNameEncoding: null));
 }
Ejemplo n.º 45
0
 public static ZipArchive Open(Stream archive, ZipArchiveMode mode, Encoding entryNameEncoding = null)
 {
     if (archive == null) throw new ArgumentNullException("archive");
     
     return new ZipArchive(archive, mode, true, entryNameEncoding);
 }
Ejemplo n.º 46
0
 public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode)
 {
     await IsZipSameAsDirAsync(archiveFile, directory, mode, requireExplicit : false, checkTimes : false);
 }
Ejemplo n.º 47
0
		public void ZipGetArchiveEntryStreamLengthPosition(ZipArchiveMode mode)
		{
			File.Copy("test.nupkg", "test2.nupkg", overwrite: true);
			using (var archive = new ZipArchive(File.Open("test2.nupkg", FileMode.Open), mode))
			{
				var entry = archive.GetEntry("_rels/.rels");
				using (var stream = entry.Open())
				{
					Assert.AreEqual(0, stream.Position);
					Assert.AreEqual(425, stream.Length);
				}

				// .NET does not support these in Read mode but we do.
				var entry2 = archive.GetEntry("modernhttpclient.nuspec");
				using (var stream = entry2.Open())
				{
					Assert.AreEqual(857, stream.Length);
					if (mode == ZipArchiveMode.Update)
					{
						Assert.AreEqual(0, stream.Position);
					}
				}
			}
			File.Delete ("test2.nupkg");	
		}
Ejemplo n.º 48
0
        public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes)
        {
            var s = await StreamHelpers.CreateTempCopyStream(archiveFile);

            IsZipSameAsDir(s, directory, mode, requireExplicit, checkTimes);
        }
Ejemplo n.º 49
0
		public ZipArchive (Stream stream, ZipArchiveMode mode,
		                   bool leaveOpen)
			: this (stream, mode)
		{
		}
Ejemplo n.º 50
0
        public static void IsZipSameAsDir(Stream archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes)
        {
            int count = 0;

            using (ZipArchive archive = new ZipArchive(archiveFile, mode))
            {
                List <FileData> files = FileData.InPath(directory);
                Assert.All <FileData>(files, (file) => {
                    count++;
                    string entryName = file.FullName;
                    if (file.IsFolder)
                    {
                        entryName += Path.DirectorySeparatorChar;
                    }
                    ZipArchiveEntry entry = archive.GetEntry(entryName);
                    if (entry == null)
                    {
                        entryName = FlipSlashes(entryName);
                        entry     = archive.GetEntry(entryName);
                    }
                    if (file.IsFile)
                    {
                        Assert.NotNull(entry);
                        long givenLength = entry.Length;

                        var buffer = new byte[entry.Length];
                        using (Stream entrystream = entry.Open())
                        {
                            entrystream.Read(buffer, 0, buffer.Length);
#if NETCOREAPP
                            uint zipcrc = entry.Crc32;
                            Assert.Equal(CRC.CalculateCRC(buffer), zipcrc);
#endif

                            if (file.Length != givenLength)
                            {
                                buffer = NormalizeLineEndings(buffer);
                            }

                            Assert.Equal(file.Length, buffer.Length);
                            ulong crc = CRC.CalculateCRC(buffer);
                            Assert.Equal(file.CRC, crc.ToString());
                        }

                        if (checkTimes)
                        {
                            const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records
                            DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution);
                            DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution);
                            Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks);
                        }

                        Assert.Equal(file.Name, entry.Name);
                        Assert.Equal(entryName, entry.FullName);
                        Assert.Equal(entryName, entry.ToString());
                        Assert.Equal(archive, entry.Archive);
                    }
                    else if (file.IsFolder)
                    {
                        if (entry == null) //entry not found
                        {
                            string entryNameOtherSlash = FlipSlashes(entryName);
                            bool isEmtpy = !files.Any(
                                f => f.IsFile &&
                                (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) ||
                                 f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase)));
                            if (requireExplicit || isEmtpy)
                            {
                                Assert.Contains("emptydir", entryName);
                            }

                            if ((!requireExplicit && !isEmtpy) || entryName.Contains("emptydir"))
                            {
                                count--; //discount this entry
                            }
                        }
                        else
                        {
                            using (Stream es = entry.Open())
                            {
                                try
                                {
                                    Assert.Equal(0, es.Length);
                                }
                                catch (NotSupportedException)
                                {
                                    try
                                    {
                                        Assert.Equal(-1, es.ReadByte());
                                    }
                                    catch (Exception)
                                    {
                                        Console.WriteLine("Didn't return EOF");
                                        throw;
                                    }
                                }
                            }
                        }
                    }
                });
                Assert.Equal(count, archive.Entries.Count);
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open.
        /// </summary>
        /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
        /// <exception cref="ArgumentNullException">The stream is null.</exception>
        /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
        /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
        /// <param name="stream">The input or output stream.</param>
        /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
        /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param>
        /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive.
        ///         ///     <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged.
        ///         However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support
        ///         UTF-8 encoding for entry names.<br />
        ///         This value is used as follows:</para>
        ///     <para><strong>Reading (opening) ZIP archive files:</strong></para>       
        ///     <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
        ///     <list>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set,
        ///         use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set,
        ///         use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item>
        ///     </list>
        ///     <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
        ///     <list>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set,
        ///         use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item>
        ///         <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set,
        ///         use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item>
        ///     </list>
        ///     <para><strong>Writing (saving) ZIP archive files:</strong></para>
        ///     <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
        ///     <list>
        ///         <item>For entry names that contain characters outside the ASCII range,
        ///         the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header,
        ///         and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item>
        ///         <item>For entry names that do not contain characters outside the ASCII range,
        ///         the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header,
        ///         and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item>
        ///     </list>
        ///     <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
        ///     <list>
        ///         <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes.
        ///         The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only
        ///         if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item>
        ///     </list>
        ///     <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>,
        ///     otherwise an <see cref="ArgumentException"/> is thrown.</para>
        /// </param>
        /// <exception cref="ArgumentException">If a Unicode encoding other than UTF-8 is specified for the <code>entryNameEncoding</code>.</exception>
        public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            Contract.EndContractBlock();

            this.EntryNameEncoding = entryNameEncoding;
            this.Init(stream, mode, leaveOpen);
        }
Ejemplo n.º 52
0
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]  // See comment in the body.
        public static ZipArchive Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
        {
            // Relies on File.Open for checking of archiveFileName

            FileMode fileMode;
            FileAccess access;
            FileShare fileShare;

            switch (mode)
            {
                case ZipArchiveMode.Read:
                    fileMode = FileMode.Open;
                    access = FileAccess.Read;
                    fileShare = FileShare.Read;
                    break;

                case ZipArchiveMode.Create:
                    fileMode = FileMode.CreateNew;
                    access = FileAccess.Write;
                    fileShare = FileShare.None;
                    break;

                case ZipArchiveMode.Update:
                    fileMode = FileMode.OpenOrCreate;
                    access = FileAccess.ReadWrite;
                    fileShare = FileShare.None;
                    break;

                default:
                    throw new ArgumentOutOfRangeException("mode");
            }

            // Surpress CA2000: fs gets passed to the new ZipArchive, which stores it internally.
            // The stream will then be owned by the archive and be disposed when the archive is disposed.        
            // If the ctor completes without throwing, we know fs has been successfully stores in the archive;
            // If the ctor throws, we need to close it here.

            FileStream fs = File.Open(archiveFileName, fileMode, access, fileShare);

            try
            {
                return new ZipArchive(fs, mode, leaveOpen: false, entryNameEncoding: entryNameEncoding);
            }
            catch
            {
                fs.Dispose();
                throw;
            }
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Initializes a new instance of ZipArchive on the given stream in the specified mode.
 /// </summary>
 /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
 /// <exception cref="ArgumentNullException">The stream is null.</exception>
 /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
 /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
 /// <param name="stream">The input or output stream.</param>
 /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
 public ZipArchive(Stream stream, ZipArchiveMode mode) : this(stream, mode, leaveOpen: false, entryNameEncoding: null) { }
Ejemplo n.º 54
0
        public static async Task <WebAssembly.Core.Array> ZipGetArchiveEntryStreamLengthPosition(ZipArchiveMode mode)
        {
            var requestTcs = new TaskCompletionSource <WebAssembly.Core.Array> ();

            using (var memoryStream = await GetPackageArchiveStreamAsync()) {
                using (var archive = new ZipArchive(memoryStream, mode)) {
                    var resultsArray = new WebAssembly.Core.Array();
                    var entry        = archive.GetEntry("_rels/.rels");

                    using (var stream = entry.Open()) {
                        resultsArray.Push((double)stream.Position);
                        resultsArray.Push((double)stream.Length);
                    }

                    var entry2 = archive.GetEntry("modernhttpclient.nuspec");
                    using (var stream = entry2.Open()) {
                        // .NET does not support these in Read mode
                        if (mode == ZipArchiveMode.Update)
                        {
                            resultsArray.Push((double)stream.Length);
                            resultsArray.Push((double)stream.Position);
                        }
                    }
                    requestTcs.SetResult(resultsArray);
                }
            }

            return(await requestTcs.Task);
        }
Ejemplo n.º 55
0
        /// <param name="useSpansForWriting">Tests the Span overloads of Write</param>
        /// <param name="writeInChunks">Writes in chunks of 5 to test Write with a nonzero offset</param>
        public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode, bool useSpansForWriting = false, bool writeInChunks = false)
        {
            var files = FileData.InPath(directory);

            using (ZipArchive archive = new ZipArchive(archiveStream, mode, true))
            {
                foreach (var i in files)
                {
                    if (i.IsFolder)
                    {
                        string entryName = i.FullName;

                        ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/");
                        e.LastWriteTime = i.LastModifiedDate;
                    }
                }

                foreach (var i in files)
                {
                    if (i.IsFile)
                    {
                        string entryName = i.FullName;

                        var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName));

                        if (installStream != null)
                        {
                            ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/'));
                            e.LastWriteTime = i.LastModifiedDate;
                            using (Stream entryStream = e.Open())
                            {
                                int bytesRead;
                                var buffer = new byte[1024];
                                if (useSpansForWriting)
                                {
                                    while ((bytesRead = installStream.Read(new Span <byte>(buffer))) != 0)
                                    {
                                        entryStream.Write(new ReadOnlySpan <byte>(buffer, 0, bytesRead));
                                    }
                                }
                                else if (writeInChunks)
                                {
                                    while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        for (int k = 0; k < bytesRead; k += 5)
                                        {
                                            entryStream.Write(buffer, k, Math.Min(5, bytesRead - k));
                                        }
                                    }
                                }
                                else
                                {
                                    while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0)
                                    {
                                        entryStream.Write(buffer, 0, bytesRead);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 56
0
 private ZipPackage(Stream stream, ZipArchiveMode mode)
     : base(stream, mode, false, (Encoding)null)
 {
 }
Ejemplo n.º 57
0
		private void CreateZip(Stream stream, ZipArchiveMode mode)
		{
			if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update)
				throw new ArgumentOutOfRangeException("mode");

			// If the mode parameter is set to Read, the stream must support reading.
			if (mode == ZipArchiveMode.Read && !stream.CanRead)
				throw new ArgumentException("Stream must support reading for Read archive mode");

			// If the mode parameter is set to Create, the stream must support writing.
			if (mode == ZipArchiveMode.Create && !stream.CanWrite)
				throw new ArgumentException("Stream must support writing for Create archive mode");

			// If the mode parameter is set to Update, the stream must support reading, writing, and seeking.
			if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek))
				throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode");

			try {
				zipFile = mode != ZipArchiveMode.Create && stream.Length != 0
					? SharpCompress.Archive.Zip.ZipArchive.Open(stream)
					: SharpCompress.Archive.Zip.ZipArchive.Create();
			} catch (Exception e) {
				throw new InvalidDataException("The contents of the stream are not in the zip archive format.", e);
			}

			entries = new Dictionary<string, ZipArchiveEntry>();
			if (Mode != ZipArchiveMode.Create) {
				foreach (var entry in zipFile.Entries) {
					var zipEntry = new ZipArchiveEntry(this, entry);
					entries[entry.Key] = zipEntry;
				}
			}
		}
Ejemplo n.º 58
0
        private void Init(Stream stream, ZipArchiveMode mode, bool leaveOpen)
        {
            Stream extraTempStream = null;

            try
            {
                _backingStream = null;

                // check stream against mode
                switch (mode)
                {
                case ZipArchiveMode.Create:
                    if (!stream.CanWrite)
                    {
                        throw new ArgumentException();
                    }
                    break;

                case ZipArchiveMode.Read:
                    if (!stream.CanRead)
                    {
                        throw new ArgumentException();
                    }
                    if (!stream.CanSeek)
                    {
                        _backingStream  = stream;
                        extraTempStream = stream = new MemoryStream();
                        _backingStream.CopyTo(stream);
                        stream.Seek(0, SeekOrigin.Begin);
                    }
                    break;

                case ZipArchiveMode.Update:
                    if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)
                    {
                        throw new ArgumentException();
                    }
                    break;

                default:
                    // still have to throw this, because stream constructor doesn't do mode argument checks
                    throw new ArgumentOutOfRangeException(nameof(mode));
                }

                _mode = mode;
                if (mode == ZipArchiveMode.Create && !stream.CanSeek)
                {
                    _archiveStream = new PositionPreservingWriteOnlyStreamWrapper(stream);
                }
                else
                {
                    _archiveStream = stream;
                }
                _archiveStreamOwner = null;
                if (mode == ZipArchiveMode.Create)
                {
                    _archiveReader = null;
                }
                else
                {
                    _archiveReader = new BinaryReader(_archiveStream);
                }
                _entries               = new List <ZipArchiveEntry>();
                _entriesCollection     = new ReadOnlyCollection <ZipArchiveEntry>(_entries);
                _entriesDictionary     = new Dictionary <string, ZipArchiveEntry>();
                _readEntries           = false;
                _leaveOpen             = leaveOpen;
                _centralDirectoryStart = 0; // invalid until ReadCentralDirectory
                _isDisposed            = false;
                _numberOfThisDisk      = 0; // invalid until ReadCentralDirectory
                _archiveComment        = null;

                switch (mode)
                {
                case ZipArchiveMode.Create:
                    _readEntries = true;
                    break;

                case ZipArchiveMode.Read:
                    ReadEndOfCentralDirectory();
                    break;

                case ZipArchiveMode.Update:
                default:
                    Debug.Assert(mode == ZipArchiveMode.Update);
                    if (_archiveStream.Length == 0)
                    {
                        _readEntries = true;
                    }
                    else
                    {
                        ReadEndOfCentralDirectory();
                        EnsureCentralDirectoryRead();
                        foreach (ZipArchiveEntry entry in _entries)
                        {
                            entry.ThrowIfNotOpenable(needToUncompress: false, needToLoadIntoMemory: true);
                        }
                    }
                    break;
                }
            }
            catch
            {
                if (extraTempStream != null)
                {
                    extraTempStream.Dispose();
                }

                throw;
            }
        }
Ejemplo n.º 59
0
 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]  // See comment in the body.
 public static ZipArchive Open(String archiveFileName, ZipArchiveMode mode)
 {
     return Open(archiveFileName, mode, entryNameEncoding: null);
 }
Ejemplo n.º 60
0
 /// <summary>
 /// Initializes a new instance of ZipArchive on the given stream in the specified mode.
 /// </summary>
 /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
 /// <exception cref="ArgumentNullException">The stream is null.</exception>
 /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
 /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
 /// <param name="stream">The input or output stream.</param>
 /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
 public ZipArchive(Stream stream, ZipArchiveMode mode) : this(stream, mode, leaveOpen : false, entryNameEncoding : null)
 {
 }