Esempio n. 1
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if (askExtractMode != AskMode.kExtract)
            {
                outStream = null;
                return(0);
            }

            if (this.streams == null)
            {
                outStream = null;
                return(0);
            }

            Stream stream = this.streams[(int)index];

            if (stream == null)
            {
                outStream = null;
                return(0);
            }

            outStream = new OutStreamWrapper(stream);

            return(0);
        }
 public void PrepareOperation(AskMode askExtractMode)
 {
     if (PrepareChecker != null)
     {
         askExtractMode = PrepareChecker(askExtractMode);
     }
 }
Esempio n. 3
0
            public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
            {
                if (k == 0)
                {
                    string FileDir = Path.GetDirectoryName(FileName);
                    if (!string.IsNullOrEmpty(FileDir))
                    {
                        Directory.CreateDirectory(FileDir);
                    }
                    FileStream = new OutStreamWrapper(File.Create(FileName));
                    outStream  = FileStream;

                    k++;
                }
                else if (index == FileNumber && askExtractMode == AskMode.kExtract && k != 0)
                {
                    string FileDir = Path.GetDirectoryName(FileName);
                    if (!string.IsNullOrEmpty(FileDir))
                    {
                        Directory.CreateDirectory(FileDir);
                    }
                    FileStream = new OutStreamWrapper(File.Create(FileName));
                    outStream  = FileStream;
                }
                else
                {
                    outStream = new OutStreamWrapper(this.memStream);
                }

                return(0);
            }
		public int GetStream(int index, out ISequentialOutStream outStream, AskMode askExtractMode)
		{
			outStream = null;
			if ((index == this.index) && (askExtractMode == AskMode.kExtract))
				outStream = new OutStreamWrapper(stream);

			return 0;
		}
		public int GetStream(int index, out ISequentialOutStream outStream, AskMode askExtractMode)
		{
			var entry = entries[index];
			outStream = null;
			var outPath = Path.Combine(path, entry.Path);
			if (entry.IsDirectory)
				Directory.CreateDirectory(outPath);
			else
				outStream = lastStream = new OutStreamWrapper(File.Create(outPath));
			return 0;
		}
Esempio n. 6
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if ((index != this.fileNumber) || (askExtractMode != AskMode.kExtract))
            {
                outStream = null;
                return(0);
            }

            outStream = new OutStreamWrapper(this.stream);

            return(0);
        }
Esempio n. 7
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if (index == FileIndex && askExtractMode == AskMode.kExtract)
            {
                Stream = new OutStreamWrapper(new MemoryStream());
                outStream = Stream;
            }
            else
                outStream = null;

            return 0;
        }
Esempio n. 8
0
            public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
            {
                var stream = _streams?.ElementAt((int)index);

                if (askExtractMode != AskMode.Extract || stream == null)
                {
                    outStream = null;
                    return(0);
                }

                outStream = new OutStreamWrapper(stream, true);
                return(0);
            }
Esempio n. 9
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if ((index == this.FileNumber) && (askExtractMode == AskMode.kExtract))
            {
                this.FileStream = new OutStreamWrapper(this.stream);
                outStream       = this.FileStream;
            }
            else
            {
                outStream = null;
            }

            return(0);
        }
 public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
 {
     outStream = null;
     if (askExtractMode == AskMode.kExtract)
     {
         this.CurrentItem = base.Items[index];
         this.BeforeExtractItem.Set();
         if (WaitHandle.WaitAny(new WaitHandle[] { this.ConfirmExtractItem, this.TerminateEvent }) != 0)
         {
             return -2147467260;
         }
         outStream = this.CurrentStream;
     }
     return 0;
 }
Esempio n. 11
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if ((index == FileNumber) && (askExtractMode == AskMode.kExtract))
              {
            string FileDir = Path.GetDirectoryName(FileName);
            if (!string.IsNullOrEmpty(FileDir))
              Directory.CreateDirectory(FileDir);
            FileStream = new OutStreamWrapper(File.Create(FileName));

            outStream = FileStream;
              }
              else
            outStream = null;

              return 0;
        }
Esempio n. 12
0
 public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
 {
     if (index != this.FileNumber || askExtractMode != AskMode.kExtract)
     {
         outStream = null;
     }
     else
     {
         string directoryName = Path.GetDirectoryName(this.FileName);
         if (!string.IsNullOrEmpty(directoryName))
         {
             Directory.CreateDirectory(directoryName);
         }
         this.FileStream = new OutStreamWrapper(File.Create(this.FileName));
         outStream       = this.FileStream;
     }
     return(0);
 }
Esempio n. 13
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if (streams != null)
            {
                if (streams[(int)index] == null)
                {
                    outStream = null;
                    return(0);
                }
                this.FileStream = new OutStreamWrapper(streams[(int)index]);
                outStream       = this.FileStream;
            }
            else
            {
                outStream = null;
            }

            return(0);
        }
Esempio n. 14
0
            public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
            {
                if ((index == FileNumber) && (askExtractMode == AskMode.kExtract))
                {
                    string FileDir = Path.GetDirectoryName(FileName);
                    if (!string.IsNullOrEmpty(FileDir))
                    {
                        Directory.CreateDirectory(FileDir);
                    }
                    FileStream = new OutStreamWrapper(File.Create(Path.Combine(this.Destinationdir, FileName)));

                    outStream = FileStream;
                }
                else
                {
                    outStream = null;
                }

                return(0);
            }
Esempio n. 15
0
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            var entry = _archive.GetEntry(index);
            var path  = (RelativePath)entry.FileName;

            if (entry.IsFolder || !_shouldExtract(path))
            {
                outStream = null;
                return(0);
            }

            Utils.Status($"Extracting {path}", Percent.FactoryPutInRange(_results.Count, _itemsCount));
            // Empty files are never extracted via a write call, so we have to fake that now
            if (entry.Size == 0)
            {
                var result = _mapFn(path, new MemoryStreamFactory(new MemoryStream(), path)).Result;
                _results.Add(path, result);
            }
            outStream = new GatheringExtractorStream <T>(this, entry, path);
            return(0);
        }
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            if ((index != this.fileNumber) || (askExtractMode != AskMode.kExtract))
            {
                outStream = null;
                return(0);
            }

            string fileDir = Path.GetDirectoryName(this.fileName);

            if (!string.IsNullOrEmpty(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }

            this.fileStream = new OutStreamWrapper(File.Create(this.fileName));

            outStream = this.fileStream;

            return(0);
        }
Esempio n. 17
0
 public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
 {
     if ((index == this.FileNumber) && (askExtractMode == AskMode.kExtract))
     {
         string directoryName = Path.GetDirectoryName(this.FileName);
         if (!string.IsNullOrEmpty(directoryName))
         {
             Directory.CreateDirectory(directoryName);
         }
         if (compressedArchiveOperator.outFileSet == "")
         {
             MessageBox.Show("Fatal Error: No outfile was sent for extraction");
         }
         if (compressedArchiveOperator.fileInRar.Replace('\\', '+') != compressedArchiveOperator.fileInRar)
         {
             compressedArchiveOperator.fileInRar = compressedArchiveOperator.fileInRar.Substring(compressedArchiveOperator.fileInRar.LastIndexOf('\\'), compressedArchiveOperator.fileInRar.Length - compressedArchiveOperator.fileInRar.LastIndexOf('\\'));
         }
         if (compressedArchiveOperator.fileInRar.Replace('/', '+') != compressedArchiveOperator.fileInRar)
         {
             compressedArchiveOperator.fileInRar = compressedArchiveOperator.fileInRar.Substring(compressedArchiveOperator.fileInRar.LastIndexOf('/'), compressedArchiveOperator.fileInRar.Length - compressedArchiveOperator.fileInRar.LastIndexOf('/'));
         }
         compressedArchiveOperator.fileInRar = Program.form.longFileName(compressedArchiveOperator.fileInRar, compressedArchiveOperator.outFileSet.Length);
         if (this.FileStream != null)
         {
             this.FileStream.Dispose();
             this.FileStream = null;
         }
         this.FileStream = new OutStreamWrapper(System.IO.File.Create(compressedArchiveOperator.outFileSet + compressedArchiveOperator.fileInRar));
         outStream       = this.FileStream;
     }
     else
     {
         outStream = null;
     }
     return(0);
 }
Esempio n. 18
0
        int IArchiveExtractCallback.GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            outStream = null;
            if (askExtractMode != AskMode.kExtract)
            {
                return(0);
            }
            var entry = this.lstEntry[(int)index];

            if (entry.IsFolder || entry.IsEncrypted)
            {
                return(0);
            }
            if (System.IO.File.Exists(entry.OutputFileName) && !this.Overwrite)
            {
                return(0);
            }
            entry.OutputStream = new QizFileStream(entry.OutputFileName, FileMode.Create, FileAccess.ReadWrite);
            outStream          = entry.OutputStream;
            return(0);
        }
 public void PrepareOperation(AskMode askExtractMode)
 {
     this.CurrentOperation = askExtractMode;
 }
Esempio n. 20
0
 public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
 {
     outStream = (ISequentialOutStream)null;
     if (askExtractMode == AskMode.Extract)
     {
         string str1 = this._Directory;
         for (int index1 = 0; index1 < 1; ++index1)
         {
             if (!this._FileIndex.HasValue)
             {
                 if (this._ActualIndexes == null || this._ActualIndexes.Contains(index))
                 {
                     PropVariant var = new PropVariant();
                     this._Archive.GetProperty(index, ItemPropId.Path, ref var);
                     string str2 = NativeMethods.SafeCast <string>(var, "");
                     if (string.IsNullOrEmpty(str2))
                     {
                         if (this._FilesCount == 1)
                         {
                             string fileName = Path.GetFileName(this._Extractor.FileName);
                             string str3     = fileName.Substring(0, fileName.LastIndexOf('.'));
                             if (!str3.EndsWith(".tar", StringComparison.OrdinalIgnoreCase))
                             {
                                 str3 += ".tar";
                             }
                             str2 = str3;
                         }
                         else
                         {
                             str2 = "[no name] " + index.ToString((IFormatProvider)CultureInfo.InvariantCulture);
                         }
                     }
                     str1 += str2;
                     this._Archive.GetProperty(index, ItemPropId.IsDirectory, ref var);
                     try
                     {
                         str1 = ArchiveExtractCallback.ValidateFileName(str1);
                     }
                     catch (Exception ex)
                     {
                         this.AddException(ex);
                         break;
                     }
                     if (!NativeMethods.SafeCast <bool>(var, false))
                     {
                         this._Archive.GetProperty(index, ItemPropId.LastWriteTime, ref var);
                         DateTime time = NativeMethods.SafeCast <DateTime>(var, DateTime.MinValue);
                         if (File.Exists(str1))
                         {
                             FileOverwriteEventArgs e = new FileOverwriteEventArgs(str1);
                             this.OnFileExists(e);
                             if (e.Cancel)
                             {
                                 this.Canceled = true;
                                 return(-1);
                             }
                             if (string.IsNullOrEmpty(e.FileName))
                             {
                                 outStream = (ISequentialOutStream)this._FakeStream;
                                 break;
                             }
                             str1 = e.FileName;
                         }
                         try
                         {
                             this._FileStream = new OutStreamWrapper((Stream)File.Create(str1), str1, time, true);
                         }
                         catch (Exception ex)
                         {
                             if (ex is FileNotFoundException)
                             {
                                 this.AddException((Exception) new IOException("The file \"" + str1 + "\" was not extracted due to the File.Create fail."));
                             }
                             else
                             {
                                 this.AddException(ex);
                             }
                             outStream = (ISequentialOutStream)this._FakeStream;
                             break;
                         }
                         this._FileStream.BytesWritten += new EventHandler <IntEventArgs>(this.IntEventArgsHandler);
                         outStream = (ISequentialOutStream)this._FileStream;
                     }
                     else if (!Directory.Exists(str1))
                     {
                         try
                         {
                             Directory.CreateDirectory(str1);
                         }
                         catch (Exception ex)
                         {
                             this.AddException(ex);
                         }
                         outStream = (ISequentialOutStream)this._FakeStream;
                     }
                 }
                 else
                 {
                     outStream = (ISequentialOutStream)this._FakeStream;
                 }
             }
             else
             {
                 uint num       = index;
                 uint?fileIndex = this._FileIndex;
                 if (((int)num != (int)fileIndex.GetValueOrDefault() ? 0 : (fileIndex.HasValue ? 1 : 0)) != 0)
                 {
                     outStream       = (ISequentialOutStream)this._FileStream;
                     this._FileIndex = new uint?();
                 }
                 else
                 {
                     outStream = (ISequentialOutStream)this._FakeStream;
                 }
             }
         }
         this._DoneRate += 1f / (float)this._FilesCount;
         FileInfoEventArgs e1 = new FileInfoEventArgs(this._Extractor.ArchiveFileData[(int)index], PercentDoneEventArgs.ProducePercentDone(this._DoneRate));
         this.OnFileExtractionStarted(e1);
         if (e1.Cancel)
         {
             if (!string.IsNullOrEmpty(str1))
             {
                 this._FileStream.Dispose();
                 if (File.Exists(str1))
                 {
                     try
                     {
                         File.Delete(str1);
                     }
                     catch (Exception ex)
                     {
                         this.AddException(ex);
                     }
                 }
             }
             this.Canceled = true;
             return(-1);
         }
     }
     return(0);
 }
Esempio n. 21
0
 public void PrepareOperation(AskMode askExtractMode)
 {
     Debug.WriteLine("ArchiveCallback->PrepareOperation: " + askExtractMode);
 }
Esempio n. 22
0
 int IArchiveExtractCallback.GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
 {
     outStream = null;
     if (index != this.index || askExtractMode != AskMode.kExtract)
     {
         return(0);
     }
     outStream = this.OutputStream;
     return(0);
 }
Esempio n. 23
0
            int IArchiveExtractCallback.GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
            {
                if (this.stream != null)
                {
                    this.stream.Dispose();
                }
                this.stream = new ObservableStream();
                var archiveFile = new SevenZipArchiveFile(this.archive, index, stream);

                this.subject.OnNext(archiveFile);
                if (archiveFile.Cancel)
                {
                    outStream = null;
                }
                else
                {
                    outStream = new OutStreamWrapper(stream);
                }
                return(0);
            }
Esempio n. 24
0
 public void PrepareOperation(AskMode askExtractMode)
 {
     Debug.WriteLine("ArchiveCallback->PrepareOperation: " + askExtractMode);
 }
Esempio n. 25
0
        private void WriteMatches(
            string input,
            Match match,
            ContentWriterOptions writerOptions,
            SearchContext context)
        {
            SearchTelemetry telemetry = context.Telemetry;

            ContentWriter  contentWriter = null;
            List <Capture> captures      = null;

            try
            {
                captures = ListCache <Capture> .GetInstance();

                GetCaptures(match, writerOptions.GroupNumber, context, isPathWritten: !Options.OmitPath, predicate: ContentFilter.Predicate, captures: captures);

                bool hasAnyFunction = Options.ModifyOptions.HasAnyFunction;

                if (hasAnyFunction ||
                    Options.AskMode == AskMode.Value ||
                    ShouldLog(Verbosity.Normal))
                {
                    if (hasAnyFunction)
                    {
                        if (_fileValues == null)
                        {
                            _fileValues = new List <string>();
                        }
                        else
                        {
                            _fileValues.Clear();
                        }

                        if (_fileStorage == null)
                        {
                            _fileStorage = new ListResultStorage(_fileValues);
                        }
                    }

                    contentWriter = ContentWriter.CreateFind(
                        contentDisplayStyle: Options.ContentDisplayStyle,
                        input: input,
                        options: writerOptions,
                        storage: (hasAnyFunction) ? _fileStorage : _storage,
                        outputInfo: Options.CreateOutputInfo(input, match),
                        writer: (hasAnyFunction) ? null : ContentTextWriter.Default,
                        ask: _askMode == AskMode.Value);
                }
                else
                {
                    contentWriter = new EmptyContentWriter(null, writerOptions);
                }

                WriteMatches(contentWriter, captures, context);

                if (hasAnyFunction)
                {
                    ConsoleColors colors         = (Options.HighlightMatch) ? Colors.Match : default;
                    ConsoleColors boundaryColors = (Options.HighlightBoundary) ? Colors.MatchBoundary : default;

                    var valueWriter = new ValueWriter(ContentTextWriter.Default, writerOptions.Indent, includeEndingIndent: false);

                    foreach (string value in _fileValues.Modify(Options.ModifyOptions))
                    {
                        Write(writerOptions.Indent, Verbosity.Normal);
                        valueWriter.Write(value, Symbols, colors, boundaryColors);
                        WriteLine(Verbosity.Normal);

                        _storage?.Add(value);
                        telemetry.MatchCount++;
                    }

                    _storageIndexes?.Add(_storage !.Count);
                }
                else
                {
                    telemetry.MatchCount += contentWriter.MatchCount;

                    if (contentWriter.MatchingLineCount >= 0)
                    {
                        if (telemetry.MatchingLineCount == -1)
                        {
                            telemetry.MatchingLineCount = 0;
                        }

                        telemetry.MatchingLineCount += contentWriter.MatchingLineCount;
                    }
                }

                if (_askMode == AskMode.Value)
                {
                    if (contentWriter is AskValueContentWriter askValueContentWriter)
                    {
                        if (!askValueContentWriter.Ask)
                        {
                            _askMode = AskMode.None;
                        }
                    }
                    else if (contentWriter is AskLineContentWriter askLineContentWriter)
                    {
                        if (!askLineContentWriter.Ask)
                        {
                            _askMode = AskMode.None;
                        }
                    }
                }
            }
            finally
            {
                contentWriter?.Dispose();

                if (captures != null)
                {
                    ListCache <Capture> .Free(captures);
                }
            }
        }
Esempio n. 26
0
            public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
            {
                //return 0x80004004L; // E_ABORT
                // S_FALSE = 1
                // S_OK = 0

                // todo: check if index matches an entry in _entries, setup the stream.
                Debug.WriteLine(String.Format("Mode: {0}; ArchiveCallback->GetStream {1}", askExtractMode, index));
                _currentIndex = index;
                if (askExtractMode == AskMode.kSkip)
                {
                    var stream = new OutStreamWrapper(new MemoryStream());
                    outStream = stream;
                    return 0;
                }
                string _transform_pattern = null;
                string _transform_text = null;

                // if transform is specified, make sure it is well formed
                if (_transform != null)
                {
                    // substitute pattern specified in _transform
                    // _transform is split by "/", i.e. "regex/replacement"
                    string[] transform_data = _transform.Split('/');
                    if (transform_data.Length == 2)
                    {
                        _transform_pattern = transform_data[0];
                        _transform_text = transform_data[1];
                        // remove any escape chars from the text
                        _transform_text = Regex.Unescape(_transform_text);
                        _command.WriteDebug("ArchiveCallback->GetStream transform_pattern: " + _transform_pattern);
                        _command.WriteDebug("ArchiveCallback->GetStream transform_text: " + _transform_text);
                    }
                    else
                    {
                        // bad transform, error...
                        _command.WriteWarning("Transform must be in the form regex/text!");
                        outStream = null;
                        return 1; // S_FALSE
                    }
                }

                try
                {
                    if ((_entries.ContainsKey(index)) && (askExtractMode == AskMode.kExtract))
                    {
                        // ensure output directory is base
                        _currentEntry = _entries[index];
                        if (_transform_pattern != null)
                        {
                            // substitute pattern specified in _transform_pattern with _transform_text
                            Regex transformer = new Regex(_transform_pattern);
                            // only run through replacement if there is a match for this entry
                            if (transformer.IsMatch(_currentEntry))
                            {
                                string newFilename = transformer.Replace(_currentEntry, _transform_text);
                                _command.WriteVerbose("Transform: " + _currentEntry + " to: " + newFilename);
                                _currentFileName = Path.Combine(_outputPath, newFilename);
                            }
                            else
                            {
                                _currentFileName = Path.Combine(_outputPath, _entries[index]);
                            }
                        }
                        else
                        {
                            _currentFileName = Path.Combine(_outputPath, _entries[index]);
                        }

                        string fileDir = Path.GetDirectoryName(_currentFileName);
                        if (!string.IsNullOrEmpty(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }
                        _fileStream = new OutStreamWrapper(File.Create(_currentFileName));
                        outStream = _fileStream;
                    }
                    else
                    {
                        outStream = null;
                    }
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    _command.WriteWarning("ArchiveCallBack->GetStream error: " + ex.ToString());
                    outStream = null;

                    return 1; // S_FALSE
                }
                return 0; // S_OK
            }
        private string Write158_AskMode(AskMode v)
        {
            switch (v)
            {
                case AskMode.kExtract:
                    return "kExtract";

                case AskMode.kTest:
                    return "kTest";

                case AskMode.kSkip:
                    return "kSkip";
            }
            long num = (long) v;
            throw base.CreateInvalidEnumValueException(num.ToString(CultureInfo.InvariantCulture), "Nomad.FileSystem.Archive.SevenZip.AskMode");
        }
Esempio n. 28
0
 void IArchiveExtractCallback.PrepareOperation(AskMode askExtractMode)
 {
 }
        /// <summary>
        /// Sets output stream for writing unpacked data
        /// </summary>
        /// <param name="index">Current file index</param>
        /// <param name="outStream">Output stream pointer</param>
        /// <param name="askExtractMode">Extraction mode</param>
        /// <returns>0 if OK</returns>
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            outStream = null;

            if (Canceled)
            {
                return(-1);
            }
            _currentIndex = (int)index;
            if (askExtractMode == AskMode.Extract)
            {
                var fileName = _directory;
                if (!_fileIndex.HasValue)
                {
                    #region Extraction to a file

                    if (_actualIndexes == null || _actualIndexes.Contains(index))
                    {
                        var data = new PropVariant();
                        _archive.GetProperty(index, ItemPropId.Path, ref data);
                        string entryName = NativeMethods.SafeCast(data, "");

                        #region Get entryName

                        if (String.IsNullOrEmpty(entryName))
                        {
                            if (_filesCount == 1)
                            {
                                var archName = Path.GetFileName(_extractor.FileName);
                                archName = archName.Substring(0, archName.LastIndexOf('.'));
                                if (!archName.EndsWith(".tar", StringComparison.OrdinalIgnoreCase))
                                {
                                    archName += ".tar";
                                }
                                entryName = archName;
                            }
                            else
                            {
                                entryName = "[no name] " + index.ToString(CultureInfo.InvariantCulture);
                            }
                        }

                        #endregion

                        try
                        {
                            fileName = Path.Combine(RemoveIllegalCharacters(_directory, true), RemoveIllegalCharacters(_directoryStructure ? entryName : Path.GetFileName(entryName)));
                            ValidateFileNameAndCreateDirectory(fileName);
                        }
                        catch (Exception e)
                        {
                            AddException(e);
                            goto FileExtractionStartedLabel;
                        }

                        _archive.GetProperty(index, ItemPropId.IsDirectory, ref data);
                        if (!NativeMethods.SafeCast(data, false))
                        {
                            #region Branch

                            _archive.GetProperty(index, ItemPropId.LastWriteTime, ref data);
                            var time = NativeMethods.SafeCast(data, DateTime.MinValue);
                            if (File.Exists(fileName))
                            {
                                var fnea = new FileOverwriteEventArgs(fileName);
                                OnFileExists(fnea);
                                if (fnea.Cancel)
                                {
                                    Canceled = true;
                                    return(-1);
                                }
                                if (String.IsNullOrEmpty(fnea.FileName))
                                {
                                    outStream = _fakeStream;

                                    goto FileExtractionStartedLabel;
                                }
                                fileName = fnea.FileName;
                            }
                            try
                            {
                                _fileStream = new OutStreamWrapper(File.Create(fileName), fileName, time, true);
                            }
                            catch (Exception e)
                            {
                                if (e is FileNotFoundException)
                                {
                                    AddException(
                                        new IOException("The file \"" + fileName +
                                                        "\" was not extracted due to the File.Create fail."));
                                }
                                else
                                {
                                    AddException(e);
                                }
                                outStream = _fakeStream;
                                goto FileExtractionStartedLabel;
                            }
                            _fileStream.BytesWritten += IntEventArgsHandler;
                            outStream = _fileStream;

                            #endregion
                        }
                        else
                        {
                            #region Branch

                            if (!Directory.Exists(fileName))
                            {
                                try
                                {
                                    Directory.CreateDirectory(fileName);
                                }
                                catch (Exception e)
                                {
                                    AddException(e);
                                }
                                outStream = _fakeStream;
                            }

                            #endregion
                        }
                    }
                    else
                    {
                        outStream = _fakeStream;
                    }

                    #endregion
                }
                else
                {
                    #region Extraction to a stream

                    if (index == _fileIndex)
                    {
                        outStream  = _fileStream;
                        _fileIndex = null;
                    }
                    else
                    {
                        outStream = _fakeStream;
                    }

                    #endregion
                }

FileExtractionStartedLabel:
                _doneRate += 1.0f / _filesCount;
                var iea = new FileInfoEventArgs(
                    _extractor.ArchiveFileData[(int)index], PercentDoneEventArgs.ProducePercentDone(_doneRate));
                OnFileExtractionStarted(iea);
                if (iea.Cancel)
                {
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        _fileStream.Dispose();
                        if (File.Exists(fileName))
                        {
                            try
                            {
                                File.Delete(fileName);
                            }
                            catch (Exception e)
                            {
                                AddException(e);
                            }
                        }
                    }
                    Canceled = true;
                    return(-1);
                }
            }
            return(0);
        }
Esempio n. 30
0
 public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
 {
     outStream = askExtractMode == AskMode.kExtract ? new OutStreamWrapper(this.stream) : null;
     return 0;
 }
Esempio n. 31
0
 public void PrepareOperation(AskMode askExtractMode)
 {
 }
        public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
        {
            outStream          = null;
            _lastEntryIndex    = index;
            _lastEntryIndexSet = true;
            _lastAskMode       = askExtractMode;

            Debug.Assert(_stream == null);
            if (_stream != null)
            {
                _stream.Dispose();
                _stream = null;
            }

            if (_extractMode == ExtractMode.UnpackedSize)
            {
                return(HRESULT.E_ABORT);
            }
            else if (askExtractMode != AskMode.Extract)
            {
                if (askExtractMode == AskMode.Skip)
                {
                    Debug.Assert(!_entries.ContainsKey(index));
                }
                return(HRESULT.S_OK);
            }
            else if (!_entries.ContainsKey(index))
            {
                Debug.Fail("Unexpected case.");
                _stream   = new OutStreamWrapper(new DummyOutStream());
                outStream = _stream;
                return(HRESULT.S_OK);
            }

            Debug.Assert(_archive != null, "_archive was not set correctly. The wrong constructor may have been used.");

            if (_targetDirectory != null)
            {
                // Writing to file system

                Debug.Assert(_extractMode == ExtractMode.ExtractToFile, "Wrong constructor used.");
                Debug.Assert(_targetDirectory.IndexOfAny(Path.GetInvalidPathChars()) == -1);

                string filePath;
                if (AutoRenamePath(LastEntryFileName, out _lastExtractedFileName))
                {
                    filePath = LastExtractedFilePath;
                }
                else
                {
                    Debug.Assert(_exception == null || _exception is PasswordRequiredException);
                    if (!(_exception is PasswordRequiredException))
                    {
                        _exception = new SevenZipException(string.Format(
                                                               "The file '{0}' cannot be extracted because the path contains invalid characters or components.", LastEntryFileName));
                    }

                    _stream   = new OutStreamWrapper(new DummyOutStream());
                    outStream = _stream;
                    return(HRESULT.S_OK);
                }

                try
                {
                    string directory = _entries[index].IsDirectory ? filePath : Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    if (_entries[index].IsDirectory)
                    {
                        Debug.Assert(_directoryEntries != null);
                        _directoryEntries[directory] = _entries[index];
                        _stream   = new OutStreamWrapper(new DummyOutStream());
                        outStream = _stream;
                        return(HRESULT.S_OK);
                    }
                    else
                    {
                        if (File.Exists(filePath))
                        {
                            FileExistsEventArgs fileExistsArgs = new FileExistsEventArgs()
                            {
                                Action          = ExtractOptionsToFileExistAction(_options),
                                TargetDirectory = _targetDirectory,
                                Entry           = _entries[_lastEntryIndex],
                            };

                            int result = InvokeEventHandler(fileExistsArgs, _archive.OnFileExists, "SevenZipArchive.FileExists");
                            if (result != HRESULT.S_OK)
                            {
                                return(result);
                            }

                            if (fileExistsArgs.Action == FileExistsAction.Throw)
                            {
                                Debug.Assert(_exception == null || _exception is PasswordRequiredException);
                                if (!(_exception is PasswordRequiredException))
                                {
                                    _exception = new SevenZipException(string.Format(
                                                                           "The file '{0}' cannot be extracted to '{1}' because a file with the same name already exists.",
                                                                           Path.GetFileName(LastExtractedFileName), directory));
                                }

                                _stream   = new OutStreamWrapper(new DummyOutStream());
                                outStream = _stream;
                                return(HRESULT.S_OK);
                            }
                            else if (fileExistsArgs.Action == FileExistsAction.Skip)
                            {
                                _lastFileSkipped = true;
                                _stream          = new OutStreamWrapper(new DummyOutStream());
                                outStream        = _stream;
                                return(HRESULT.S_OK);
                            }
                        }
                        _stream   = new OutStreamWrapper(File.Create(filePath));
                        outStream = _stream;
                        return(HRESULT.S_OK);
                    }
                }
                catch (Exception e)
                {
                    Debug.Assert(_exception == null || _exception is PasswordRequiredException);
                    if (!(_exception is PasswordRequiredException))
                    {
                        _exception = new SevenZipException(string.Format(
                                                               "An exception occured while extracting the file '{0}'.", LastEntryFileName), e);
                    }

                    _stream   = new OutStreamWrapper(new DummyOutStream());
                    outStream = _stream;
                    return(HRESULT.S_OK);
                }
            }
            else
            {
                // Writing to stream

                Debug.Assert(_extractMode == ExtractMode.ExtractToStream, "Wrong constructor used.");
                Debug.Assert(_targetStream != null);
                _stream   = new OutStreamWrapper(_targetStream, false);
                outStream = _stream;
                return(HRESULT.S_OK);
            }
        }
Esempio n. 33
0
 public void PrepareOperation(AskMode askExtractMode)
 {
 }
Esempio n. 34
0
            public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
            {
                //return 0x80004004L; // E_ABORT
                // S_FALSE = 1
                // S_OK = 0

                // todo: check if index matches an entry in _entries, setup the stream.
                Debug.WriteLine(String.Format("Mode: {0}; ArchiveCallback->GetStream {1}", askExtractMode, index));
                _currentIndex = index;
                if (askExtractMode == AskMode.kSkip)
                {
                    var stream = new OutStreamWrapper(new MemoryStream());
                    outStream = stream;
                    return(0);
                }
                string _transform_pattern = null;
                string _transform_text    = null;

                // if transform is specified, make sure it is well formed
                if (_transform != null)
                {
                    // substitute pattern specified in _transform
                    // _transform is split by "/", i.e. "regex/replacement"
                    string[] transform_data = _transform.Split('/');
                    if (transform_data.Length == 2)
                    {
                        _transform_pattern = transform_data[0];
                        _transform_text    = transform_data[1];
                        // remove any escape chars from the text
                        _transform_text = Regex.Unescape(_transform_text);
                        _command.WriteDebug("ArchiveCallback->GetStream transform_pattern: " + _transform_pattern);
                        _command.WriteDebug("ArchiveCallback->GetStream transform_text: " + _transform_text);
                    }
                    else
                    {
                        // bad transform, error...
                        _command.WriteWarning("Transform must be in the form regex/text!");
                        outStream = null;
                        return(1); // S_FALSE
                    }
                }

                try
                {
                    if ((_entries.ContainsKey(index)) && (askExtractMode == AskMode.kExtract))
                    {
                        // ensure output directory is base
                        _currentEntry = _entries[index];
                        if (_transform_pattern != null)
                        {
                            // substitute pattern specified in _transform_pattern with _transform_text
                            Regex transformer = new Regex(_transform_pattern);
                            // only run through replacement if there is a match for this entry
                            if (transformer.IsMatch(_currentEntry))
                            {
                                string newFilename = transformer.Replace(_currentEntry, _transform_text);
                                _command.WriteVerbose("Transform: " + _currentEntry + " to: " + newFilename);
                                _currentFileName = Path.Combine(_outputPath, newFilename);
                            }
                            else
                            {
                                _currentFileName = Path.Combine(_outputPath, _entries[index]);
                            }
                        }
                        else
                        {
                            _currentFileName = Path.Combine(_outputPath, _entries[index]);
                        }

                        string fileDir = Path.GetDirectoryName(_currentFileName);
                        if (!string.IsNullOrEmpty(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }
                        _fileStream = new OutStreamWrapper(File.Create(_currentFileName));
                        outStream   = _fileStream;
                    }
                    else
                    {
                        outStream = null;
                    }
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    _command.WriteWarning("ArchiveCallBack->GetStream error: " + ex.ToString());
                    outStream = null;

                    return(1); // S_FALSE
                }
                return(0);     // S_OK
            }