示例#1
0
 private byte[] ReadAllBytes()
 {
     using (var ms = new MemoryStream())
     {
         _archiveIterator.ExtractCurrentFile(ms, null);
         return(ms.Length > 0 ? ms.ToArray() : null);
     }
 }
        private void ExtractFile()
        {
            ArchiveIterator iterator = null;

            try
            {
                using (Stream stream = new FileStream(outFileName, FileMode.Open, FileAccess.Read))
                {
                    iterator = ArchiveFactory.Reader(ArchiveFactory.Type.Zip, stream);
                    DotNetZipZipIterator zipIterator = iterator as DotNetZipZipIterator;
                    if (zipIterator != null)
                    {
                        zipIterator.CurrentFileExtractProgressChanged +=
                            archiveIterator_CurrentFileExtractProgressChanged;
                    }

                    while (iterator.HasNext())
                    {
                        if (Path.GetExtension(iterator.CurrentFileName()) == ".xsupdate")
                        {
                            string path = Path.Combine(Path.GetDirectoryName(outFileName), iterator.CurrentFileName());

                            using (Stream outputStream = new FileStream(path, FileMode.Create))
                            {
                                iterator.ExtractCurrentFile(outputStream);
                                PatchPath = path;
                                break;
                            }
                        }
                    }

                    if (zipIterator != null)
                    {
                        zipIterator.CurrentFileExtractProgressChanged -=
                            archiveIterator_CurrentFileExtractProgressChanged;
                    }
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("Exception occurred when extracting downloaded archive: {0}", e.Message);
                throw new Exception(Messages.DOWNLOAD_AND_EXTRACT_ACTION_EXTRACTING_ERROR);
            }
            finally
            {
                if (iterator != null)
                {
                    iterator.Dispose();
                }
                File.Delete(outFileName);
            }

            if (string.IsNullOrEmpty(PatchPath))
            {
                MarkCompleted(new Exception(Messages.DOWNLOAD_AND_EXTRACT_ACTION_FILE_NOT_FOUND));
                log.DebugFormat("File '{0}{1}' could not be located in downloaded archive", updateName, ".xsupdate");
            }
        }
 private string GetXmlStringFromTarXVA()
 {
     using (Stream stream = new FileStream(textBoxFile.Text, FileMode.Open, FileAccess.Read)) {
         ArchiveIterator iterator = ArchiveFactory.Reader(ArchiveFactory.Type.Tar, stream);
         if (iterator.HasNext())
         {
             Stream ofs = new MemoryStream();
             iterator.ExtractCurrentFile(ofs);
             ofs.Position = 0;
             return(new StreamReader(ofs).ReadToEnd());
         }
         return(String.Empty);
     }
 }
示例#4
0
        // This test knows the contents of the file written in the archive
        private void RereadAnArchiveAndTest(string archiveName)
        {
            List <string> expectedDirs = new List <string>()
            {
                "adir/",
                "adir2/a/"
            };

            List <string> expectedFiles = new List <string>()
            {
                "tf1",
                "adir2/a/tf2"
            };

            using (FileStream fs = File.OpenRead(archiveName))
            {
                reader.SetBaseStream(fs);
                while (reader.HasNext())
                {
                    if (reader.IsDirectory() && expectedDirs.Contains(reader.CurrentFileName()))
                    {
                        expectedDirs.Remove(reader.CurrentFileName());
                    }

                    if (!reader.IsDirectory() && expectedFiles.Contains(reader.CurrentFileName()))
                    {
                        expectedFiles.Remove(reader.CurrentFileName());
                        using (MemoryStream ms = new MemoryStream())
                        {
                            reader.ExtractCurrentFile(ms);
                            Assert.IsTrue(ms.Length > 0, "Extracted file contents have data");
                        }
                    }
                }

                Assert.AreEqual(0, expectedFiles.Count, "Expected files count");
                Assert.AreEqual(0, expectedDirs.Count, "Expected dir count");
            }

            Reader.Dispose();
        }
        private void ExtractFile()
        {
            ArchiveIterator iterator = null;

            try
            {
                using (Stream stream = new FileStream(outputFileName, FileMode.Open, FileAccess.Read))
                {
                    iterator = ArchiveFactory.Reader(ArchiveFactory.Type.Zip, stream);
                    DotNetZipZipIterator zipIterator = iterator as DotNetZipZipIterator;
                    if (zipIterator != null)
                    {
                        zipIterator.CurrentFileExtractProgressChanged +=
                            archiveIterator_CurrentFileExtractProgressChanged;
                    }

                    while (iterator.HasNext())
                    {
                        string currentExtension = Path.GetExtension(iterator.CurrentFileName());

                        if (updateFileSuffixes.Any(item => item == currentExtension))
                        {
                            string path = downloadUpdate
                                ? Path.Combine(Path.GetDirectoryName(outputFileName), iterator.CurrentFileName())
                                : Path.Combine(Path.GetTempPath(), iterator.CurrentFileName());

                            log.InfoFormat(
                                "Found '{0}' in the downloaded archive when looking for a '{1}' file. Extracting...",
                                iterator.CurrentFileName(), currentExtension);

                            using (Stream outputStream = new FileStream(path, FileMode.Create))
                            {
                                iterator.ExtractCurrentFile(outputStream);
                                PatchPath = path;

                                log.InfoFormat("Update file extracted to '{0}'", path);

                                break;
                            }
                        }
                    }

                    if (zipIterator != null)
                    {
                        zipIterator.CurrentFileExtractProgressChanged -=
                            archiveIterator_CurrentFileExtractProgressChanged;
                    }
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("Exception occurred when extracting downloaded archive: {0}", e.Message);
                throw new Exception(Messages.DOWNLOAD_AND_EXTRACT_ACTION_EXTRACTING_ERROR);
            }
            finally
            {
                if (iterator != null)
                {
                    iterator.Dispose();
                }

                if (downloadUpdate)
                {
                    try { File.Delete(outputFileName); }
                    catch { }
                }
            }

            if (string.IsNullOrEmpty(PatchPath) && downloadUpdate)
            {
                MarkCompleted(new Exception(Messages.DOWNLOAD_AND_EXTRACT_ACTION_FILE_NOT_FOUND));
                log.InfoFormat(
                    "The downloaded archive does not contain a file with any of the following extensions: {0}",
                    string.Join(", ", updateFileSuffixes));
            }
        }
        protected override void Run()
        {
            // The directory in which we assemble the log files from the server before repackaging them
            // in a single zip file.
            string extractTempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                // Calculate total bytes to save
                long bytesToExtract = 1, bytesExtracted = 0;
                foreach (string inputFile in Directory.GetFiles(_inputTempFolder))
                {
                    bytesToExtract += new FileInfo(inputFile).Length;
                }

                // Create temp dir for extracted stuff
                if (Directory.Exists(extractTempDir))
                {
                    Directory.Delete(extractTempDir);
                }
                Directory.CreateDirectory(extractTempDir);

                // Extract each of the raw server files to the temp extraction directory
                foreach (string inputFile in Directory.GetFiles(_inputTempFolder))
                {
                    if (inputFile.ToLowerInvariant().EndsWith(".tar"))
                    {
                        // Un-tar it. SharpZipLib doesn't account for illegal filenames or characters in
                        // filenames (e.g. ':'in Windows), so first we stream the tar to a new tar,
                        // sanitizing any bad filenames as we go.

                        // We also need to record the modification times of all the files, so that we can
                        // restore them into the final zip.

                        string outFilename = inputFile.Substring(0, inputFile.Length - 4);
                        if (outFilename.Length == 0)
                        {
                            outFilename = Path.GetRandomFileName();
                        }
                        string outputDir = Path.Combine(extractTempDir, Path.GetFileName(outFilename));

                        string sanitizedTar = Path.GetTempFileName();

                        using (ArchiveIterator tarIterator = ArchiveFactory.Reader(ArchiveFactory.Type.Tar, File.OpenRead(inputFile)))
                        {
                            using (ArchiveWriter tarWriter = ArchiveFactory.Writer(ArchiveFactory.Type.Tar, File.OpenWrite(sanitizedTar)))
                            {
                                Dictionary <string, string> usedNames = new Dictionary <string, string>();
                                while (tarIterator.HasNext())
                                {
                                    if (Cancelling)
                                    {
                                        throw new CancelledException();
                                    }

                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        tarIterator.ExtractCurrentFile(ms);
                                        string saneName = SanitizeTarName(tarIterator.CurrentFileName(), usedNames);
                                        tarWriter.Add(ms, saneName);
                                        ModTimes[Path.Combine(outputDir, saneName)] = tarIterator.CurrentFileModificationTime();
                                    }
                                }
                            }
                        }

                        // Now extract the sanitized tar
                        using (FileStream fs = File.OpenRead(sanitizedTar))
                        {
                            using (ArchiveIterator tarIterator = ArchiveFactory.Reader(ArchiveFactory.Type.Tar, fs))
                            {
                                Directory.CreateDirectory(outputDir);
                                tarIterator.ExtractAllContents(outputDir);
                                bytesToCompress += Core.Helpers.GetDirSize(new DirectoryInfo(outputDir));
                            }
                        }
                    }
                    else
                    {
                        // Just copy vanilla input files unmodified to the temp directory
                        string outputFile = Path.Combine(extractTempDir, Path.GetFileName(inputFile));
                        File.Copy(inputFile, outputFile);
                        ModTimes[outputFile] = new FileInfo(inputFile).LastWriteTimeUtc;
                        bytesToCompress     += new FileInfo(outputFile).Length;
                    }

                    bytesExtracted += new FileInfo(inputFile).Length;
                    File.Delete(inputFile);
                    this.PercentComplete = (int)(50.0 * bytesExtracted / bytesToExtract);

                    if (Cancelling)
                    {
                        throw new CancelledException();
                    }
                }

                // Now zip up all the temporarily extracted files into a single zip file for the user
                log.DebugFormat("Packing {0} of bug report files into zip file {1}",
                                Util.DiskSizeString(bytesToCompress), _destFile);

                LogDescriptionChanges = false;
                try
                {
                    ZipToOutputFile(extractTempDir);
                    PercentComplete = 100;

                    // Only cleanup files if it succeeded (or cancelled)
                    CleanupFiles(extractTempDir);
                }
                finally
                {
                    LogDescriptionChanges = true;
                }

                if (Cancelling)
                {
                    throw new CancelledException();
                }
            }
            catch (CancelledException)
            {
                CleanupFiles(extractTempDir, true);

                throw;
            }
            catch (Exception exn)
            {
                ZipToOutputFile(_inputTempFolder);
                PercentComplete = 100;
                log.ErrorFormat("An exception was trapped while creating a server status report: " + exn.Message);
                throw new Exception(Messages.STATUS_REPORT_ZIP_FAILED);
            }
        }