Example #1
0
        public static ZipSegmentedStream ForWriting(ZipSegmentedStreamManager manager, int maxSegmentSize)
        {
            ZipSegmentedStream zss = new ZipSegmentedStream()
            {
                rwMode          = RwMode.Write,
                CurrentSegment  = 0,
                _maxSegmentSize = maxSegmentSize,
                _manager        = manager
            };

            zss._SetWriteStream(0);

            // Console.WriteLine("ZSS: ForWriting ({0})",
            //                    Path.GetFileName(zss.CurrentName));

            return(zss);
        }
Example #2
0
        public void Save(ZipSegmentedStreamManager segmentsManager)
        {
            if (segmentsManager == null)
            {
                throw new ArgumentNullException("segmentsManager");
            }

            // if we had a filename to save to, we are now obliterating it.
            _name = null;

            _writeSegmentsManager = segmentsManager;
            _writestream          = null;

            _contentsChanged   = true;
            _WriteStreamIsOurs = false;
            Save();
        }
        public static ZipSegmentedStream ForReading(ZipSegmentedStreamManager manager,
                                                    uint initialDiskNumber,
                                                    uint maxDiskNumber)
        {
            ZipSegmentedStream zss = new ZipSegmentedStream()
                {
                    rwMode = RwMode.ReadOnly,
                    CurrentSegment = initialDiskNumber,
                    _maxDiskNumber = maxDiskNumber,
                    _manager = manager
                };

            // Console.WriteLine("ZSS: ForReading ({0})",
            //                    Path.GetFileName(zss.CurrentName));

            zss._SetReadStream();

            return zss;
        }
Example #4
0
        public static ZipSegmentedStream ForReading(ZipSegmentedStreamManager manager,
                                                    uint initialDiskNumber,
                                                    uint maxDiskNumber)
        {
            ZipSegmentedStream zss = new ZipSegmentedStream()
            {
                rwMode         = RwMode.ReadOnly,
                CurrentSegment = initialDiskNumber,
                _maxDiskNumber = maxDiskNumber,
                _manager       = manager
            };

            // Console.WriteLine("ZSS: ForReading ({0})",
            //                    Path.GetFileName(zss.CurrentName));

            zss._SetReadStream();

            return(zss);
        }
        /// <summary>
        /// Reads a zip archive from a stream, using the specified text Encoding, the
        /// specified TextWriter for status messages,
        /// and the specified ReadProgress event handler.
        /// </summary>
        ///
        /// <remarks>
        /// <para>
        /// Reading of zip content begins at the current position in the stream.  This
        /// means if you have a stream that concatenates regular data and zip data, if
        /// you position the open, readable stream at the start of the zip data, you
        /// will be able to read the zip archive using this constructor, or any of the
        /// ZipFile constructors that accept a <see cref="System.IO.Stream" /> as
        /// input. Some examples of where this might be useful: the zip content is
        /// concatenated at the end of a regular EXE file, as some self-extracting
        /// archives do.  (Note: SFX files produced by DotNetZip do not work this
        /// way). Another example might be a stream being read from a database, where
        /// the zip content is embedded within an aggregate stream of data.
        /// </para>
        /// </remarks>
        ///
        /// <param name="zipStream">the stream containing the zip data.</param>
        ///
        /// <param name="statusMessageWriter">
        /// The <c>System.IO.TextWriter</c> to which verbose status messages are written
        /// during operations on the <c>ZipFile</c>.  For example, in a console
        /// application, System.Console.Out works, and will get a message for each entry
        /// added to the ZipFile.  If the TextWriter is <c>null</c>, no verbose messages
        /// are written.
        /// </param>
        ///
        /// <param name="encoding">
        /// The text encoding to use when reading entries that do not have the UTF-8
        /// encoding bit set.  Be careful specifying the encoding.  If the value you use
        /// here is not the same as the Encoding used when the zip archive was created
        /// (possibly by a different archiver) you will get unexpected results and
        /// possibly exceptions.  See the <see cref="ProvisionalAlternateEncoding"/>
        /// property for more information.
        /// </param>
        ///
        /// <param name="readProgress">
        /// An event handler for Read operations.
        /// </param>
        ///
        /// <returns>an instance of ZipFile</returns>
        private static ZipFile Read(Stream zipStream,
                                    ZipSegmentedStreamManager segmentsManager,
                                    TextWriter statusMessageWriter,
                                    System.Text.Encoding encoding,
                                    EventHandler <ReadProgressEventArgs> readProgress,
                                    bool fullScan)
        {
            if (zipStream == null)
            {
                throw new ArgumentNullException("zipStream");
            }

            ZipFile zf = new ZipFile();

            zf._StatusMessageTextWriter = statusMessageWriter;
            zf._alternateEncoding       = encoding ?? ZipFile.DefaultEncoding;
            zf._alternateEncodingUsage  = ZipOption.Always;
            if (readProgress != null)
            {
                zf.ReadProgress += readProgress;
            }
            zf._readstream = (zipStream.Position == 0L)
                ? zipStream
                : new OffsetStream(zipStream);
            zf._readSegmentsManager = segmentsManager;
            zf._ReadStreamIsOurs    = false;
            if (zf.Verbose)
            {
                zf._StatusMessageTextWriter.WriteLine("reading from stream...");
            }

            if (fullScan)
            {
                ReadIntoInstance_Orig(zf);
            }
            else
            {
                ReadIntoInstance(zf);
            }
            return(zf);
        }
        public static ZipSegmentedStream ForWriting(ZipSegmentedStreamManager manager, int maxSegmentSize)
        {
            ZipSegmentedStream zss = new ZipSegmentedStream()
                {
                    rwMode = RwMode.Write,
                    CurrentSegment = 0,
                    _maxSegmentSize = maxSegmentSize,
                    _manager = manager
                };

            zss._SetWriteStream(0);

            // Console.WriteLine("ZSS: ForWriting ({0})",
            //                    Path.GetFileName(zss.CurrentName));

            return zss;
        }
        /// <summary>
        ///   Sort-of like a factory method, ForUpdate is used only when
        ///   the application needs to update the zip entry metadata for
        ///   a segmented zip file, when the starting segment is earlier
        ///   than the ending segment, for a particular entry.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     The update is always contiguous, never rolls over.  As a
        ///     result, this method doesn't need to return a ZSS; it can
        ///     simply return a FileStream.  That's why it's "sort of"
        ///     like a Factory method.
        ///   </para>
        ///   <para>
        ///     Caller must Close/Dispose the stream object returned by
        ///     this method.
        ///   </para>
        /// </remarks>
        public static Stream ForUpdate(ZipSegmentedStreamManager manager, uint diskNumber)
        {

            // Console.WriteLine("ZSS: ForUpdate ({0})",
            //                   Path.GetFileName(fname));

            // This class assumes that the update will not expand the
            // size of the segment. Update is used only for an in-place
            // update of zip metadata. It never will try to write beyond
            // the end of a segment.

            return manager.OpenSegment(diskNumber, 0, true);
        }
Example #8
0
        /// <summary>
        /// Reads a zip archive from a stream, using the specified text Encoding, the
        /// specified TextWriter for status messages,
        /// and the specified ReadProgress event handler.
        /// </summary>
        ///
        /// <remarks>
        /// <para>
        /// Reading of zip content begins at the current position in the stream.  This
        /// means if you have a stream that concatenates regular data and zip data, if
        /// you position the open, readable stream at the start of the zip data, you
        /// will be able to read the zip archive using this constructor, or any of the
        /// ZipFile constructors that accept a <see cref="System.IO.Stream" /> as
        /// input. Some examples of where this might be useful: the zip content is
        /// concatenated at the end of a regular EXE file, as some self-extracting
        /// archives do.  (Note: SFX files produced by DotNetZip do not work this
        /// way). Another example might be a stream being read from a database, where
        /// the zip content is embedded within an aggregate stream of data.
        /// </para>
        /// </remarks>
        ///
        /// <param name="zipStream">the stream containing the zip data.</param>
        ///
        /// <param name="statusMessageWriter">
        /// The <c>System.IO.TextWriter</c> to which verbose status messages are written
        /// during operations on the <c>ZipFile</c>.  For example, in a console
        /// application, System.Console.Out works, and will get a message for each entry
        /// added to the ZipFile.  If the TextWriter is <c>null</c>, no verbose messages
        /// are written.
        /// </param>
        ///
        /// <param name="encoding">
        /// The text encoding to use when reading entries that do not have the UTF-8
        /// encoding bit set.  Be careful specifying the encoding.  If the value you use
        /// here is not the same as the Encoding used when the zip archive was created
        /// (possibly by a different archiver) you will get unexpected results and
        /// possibly exceptions.  See the <see cref="ProvisionalAlternateEncoding"/>
        /// property for more information.
        /// </param>
        ///
        /// <param name="readProgress">
        /// An event handler for Read operations.
        /// </param>
        ///
        /// <returns>an instance of ZipFile</returns>
        private static ZipFile Read(Stream zipStream,
                                   ZipSegmentedStreamManager segmentsManager,
                                   TextWriter statusMessageWriter,
                                   System.Text.Encoding encoding,
                                   EventHandler<ReadProgressEventArgs> readProgress,
                                   bool fullScan)
        {
            if (zipStream == null)
                throw new ArgumentNullException("zipStream");

            ZipFile zf = new ZipFile();
            zf._StatusMessageTextWriter = statusMessageWriter;
            zf._alternateEncoding = encoding ?? ZipFile.DefaultEncoding;
            zf._alternateEncodingUsage = ZipOption.Always;
            if (readProgress != null)
                zf.ReadProgress += readProgress;
            zf._readstream = (zipStream.Position == 0L)
                ? zipStream
                : new OffsetStream(zipStream);
            zf._readSegmentsManager = segmentsManager;
            zf._ReadStreamIsOurs = false;
            if (zf.Verbose) zf._StatusMessageTextWriter.WriteLine("reading from stream...");

            if (fullScan)
            ReadIntoInstance_Orig(zf);
            else
            ReadIntoInstance(zf);
            return zf;
        }
Example #9
0
        public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager, ReadOptions options)
        {
            if (segmentsManager == null)
                throw new ArgumentNullException("segmentsManager");

            return Read(zipStream,
                        segmentsManager,
                        options.StatusMessageWriter,
                        options.Encoding,
                        options.ReadProgress,
                        options.FullScan);
        }
Example #10
0
        public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager)
        {
            if (segmentsManager == null)
                throw new ArgumentNullException("segmentsManager");

            return Read(zipStream, segmentsManager, null, null, null, false);
        }
Example #11
0
        public void Save(ZipSegmentedStreamManager segmentsManager)
        {
            if (segmentsManager == null)
                throw new ArgumentNullException("segmentsManager");

            // if we had a filename to save to, we are now obliterating it.
            _name = null;

            _writeSegmentsManager = segmentsManager;
            _writestream = null;

            _contentsChanged = true;
            _WriteStreamIsOurs = false;
            Save();
        }
        /// <summary>
        /// Save the file to a new zipfile, with the given name.
        /// </summary>
        ///
        /// <remarks>
        /// <para>
        /// This method allows the application to explicitly specify the name of the zip
        /// file when saving. Use this when creating a new zip file, or when
        /// updating a zip archive.
        /// </para>
        ///
        /// <para>
        /// An application can also save a zip archive in several places by calling this
        /// method multiple times in succession, with different filenames.
        /// </para>
        ///
        /// <para>
        /// The <c>ZipFile</c> instance is written to storage, typically a zip file in a
        /// filesystem, only when the caller calls <c>Save</c>.  The Save operation writes
        /// the zip content to a temporary file, and then renames the temporary file
        /// to the desired name. If necessary, this method will delete a pre-existing file
        /// before the rename.
        /// </para>
        ///
        /// </remarks>
        ///
        /// <exception cref="System.ArgumentException">
        /// Thrown if you specify a directory for the filename.
        /// </exception>
        ///
        /// <param name="fileName">
        /// The name of the zip archive to save to. Existing files will
        /// be overwritten with great prejudice.
        /// </param>
        ///
        /// <example>
        /// This example shows how to create and Save a zip file.
        /// <code>
        /// using (ZipFile zip = new ZipFile())
        /// {
        ///   zip.AddDirectory(@"c:\reports\January");
        ///   zip.Save("January.zip");
        /// }
        /// </code>
        ///
        /// <code lang="VB">
        /// Using zip As New ZipFile()
        ///   zip.AddDirectory("c:\reports\January")
        ///   zip.Save("January.zip")
        /// End Using
        /// </code>
        ///
        /// </example>
        ///
        /// <example>
        /// This example shows how to update a zip file.
        /// <code>
        /// using (ZipFile zip = ZipFile.Read("ExistingArchive.zip"))
        /// {
        ///   zip.AddFile("NewData.csv");
        ///   zip.Save("UpdatedArchive.zip");
        /// }
        /// </code>
        ///
        /// <code lang="VB">
        /// Using zip As ZipFile = ZipFile.Read("ExistingArchive.zip")
        ///   zip.AddFile("NewData.csv")
        ///   zip.Save("UpdatedArchive.zip")
        /// End Using
        /// </code>
        ///
        /// </example>
        public static void Save(this ZipFile zipFile, String fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            string fullPath = GetFullPath(fileName);

            if (FileSystem.Current.GetFolderFromPathAsync(fullPath).ExecuteSync() != null)
            {
                throw new ZipException("Bad Directory", new ArgumentException("That name specifies an existing directory. Please specify a filename.", "fileName"));
            }

            var fullDirectoryName = Path.GetDirectoryName(fullPath);
            var directoryName     = Path.GetDirectoryName(fileName);
            var folder            = FileSystem.Current.GetFolderFromPathAsync(fullDirectoryName).ExecuteSync();

            if (folder == null)
            {
                throw new ZipException("Bad Directory", new ArgumentException(string.Format("That folder ({0}) does not exist!", directoryName)));
            }

            // check up here so we may shortcut some IO operations in the future :)
            var fileExists = folder.CheckExistsAsync(fullPath).ExecuteSync() == ExistenceCheckResult.FileExists;

            // write to a temporary file so that we can read from the same zip when saving
            var tmpName = Path.GetRandomFileName();

            try
            {
                ZipSegmentedStreamManager segmentsManager = null;

                if (zipFile.MaxOutputSegmentSize != 0)
                {
                    // save segmented files using the segments manager
                    var manager = new FileSystemZipSegmentedStreamManager(fullPath);
                    segmentsManager = manager;
                    zipFile.Save(segmentsManager);
                    tmpName = manager.TemporaryName;
                }
                else
                {
                    // save
                    var tmpFile = folder.CreateFileAsync(tmpName, CreationCollisionOption.ReplaceExisting).ExecuteSync();
                    tmpName = tmpFile.Path;
                    using (var tmpStream = tmpFile.OpenAsync(FileAccess.ReadAndWrite).ExecuteSync())
                    {
                        zipFile.Save(tmpStream);
                    }
                }

                // if it wasn't canceled
                if (!zipFile.IsSaveOperationCanceled())
                {
                    // disconnect from the stream
                    zipFile.SetUnderlyingZipStream(null);
                    // move the temporary file into position
                    zipFile.OnSaveEvent(ZipProgressEventType.Saving_BeforeRenameTempArchive);
                    ZipEntryExtensions.MoveFileInPlace(fileExists, fullPath, tmpName);
                    zipFile.OnSaveEvent(ZipProgressEventType.Saving_AfterRenameTempArchive);
                    // and now set the read stream to be that of the new file
                    var targetFile = FileSystem.Current.GetFileFromPathAsync(fullPath).ExecuteSync();
                    var fileStream = targetFile.OpenAsync(FileAccess.Read).ExecuteSync();
                    zipFile.SetUnderlyingZipSegmentedStreamManager(segmentsManager);
                    zipFile.SetUnderlyingZipStream(fileStream);
                    zipFile.SetShouldDisposeReadStream(true);
                    zipFile.Name = fullPath;

                    // so we can shortcut the existance checks
                    tmpName = null;
                }
            }
            finally
            {
                // An exception has occurred. If the file exists, check
                // to see if it existed before we tried extracting.  If
                // it did not, attempt to remove the target file. There
                // is a small possibility that the existing file has
                // been extracted successfully, overwriting a previously
                // existing file, and an exception was thrown after that
                // but before final completion (setting times, etc). In
                // that case the file will remain, even though some
                // error occurred.  Nothing to be done about it.
                if (tmpName != null)
                {
                    var tmpFile = folder.GetFileAsync(tmpName).ExecuteSync();
                    tmpFile.DeleteAsync();
                }
            }
        }
Example #13
0
 public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager, ReadOptions options)
 {
     return ZipFile.Read(zipStream, segmentsManager, options);
 }
Example #14
0
 public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager)
 {
     return ZipFile.Read(zipStream, segmentsManager);
 }
 public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager, ReadOptions options)
 {
     return(ZipFile.Read(zipStream, segmentsManager, options));
 }
 public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager)
 {
     return(ZipFile.Read(zipStream, segmentsManager));
 }