Inheritance: IDisposable
Example #1
0
        protected override async Task<bool> CheckAndUpdateIfNeededInner() {
            if (InstalledVersion == null) return false;

            var data = await CmApiProvider.GetDataAsync($"locales/update/{SettingsHolder.Locale.LocaleName}/{InstalledVersion}");
            if (data == null) {
                LatestError = ToolsStrings.BaseUpdater_CannotDownloadInformation;
                Logging.Warning("Cannot get locales/update");
                return false;
            }

            if (data.Length == 0) {
                return false;
            }

            try {
                LocalePackageManifest manifest;
                using (var memory = new MemoryStream(data))
                using (var updateZip = new ZipArchive(memory)) {
                    manifest = LocalePackageManifest.FromArchive(updateZip);
                    if (manifest == null) throw new Exception("Manifest is missing");
                }

                var package = FilesStorage.Instance.GetFilename("Locales", manifest.Id + ".pak");
                await FileUtils.WriteAllBytesAsync(package, data);
                Logging.Write("Locale updated");

                InstalledVersion = manifest.Version;
                return true;
            } catch (Exception e) {
                Logging.Warning("Cannot update locale: " + e);
                return false;
            }
        }
        IEnumerable<PackageEntry> GetEntries(ZipArchive zipArchive)
        {
            IList<PackageEntry> result = new List<PackageEntry>();

            foreach (ZipArchiveEntry entry in zipArchive.Entries)
            {
                if (entry.FullName.EndsWith("/.rels", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (entry.FullName.EndsWith("[Content_Types].xml", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (entry.FullName.EndsWith(".psmdcp", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                result.Add(new PackageEntry(entry));
            }

            return result;
        }
        public static async System.Threading.Tasks.Task<string> GetRootFilePathAsync(ZipArchive epubArchive)
        {
            //Checking if file exist
            const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml";

            ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH);
            string full_path = string.Empty;

            if (containerFileEntry == null)
                throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH));

            //Loading container.xml to memmory...
            using (Stream containerStream = containerFileEntry.Open())
            {
                // ...and trying to parse it in order to get the full path to the .opf file, like full-path="SomeFolder/SomeFileWithContent.opf"
                full_path = await XmlUtils.GetFilePathAttributeAsync(containerStream);
            }
            //Checking if the problem exist...
            if (full_path == "full-path attribute not found" || full_path == "Yes, rootfile not found...")
            {
                Debug.WriteLine(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path));
                throw new Exception(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path));
            }
                
            return full_path;

            //Initial code sucks and is not compatible with Win 8.1 runtime framework
            /*
            xmlNamespaceManager.AddNamespace("cns", "urn:oasis:names:tc:opendocument:xmlns:container");
            XmlNode rootFileNode = containerDocument.DocumentElement.SelectSingleNode("/cns:container/cns:rootfiles/cns:rootfile", xmlNamespaceManager);
            return rootFileNode.Attributes["full-path"].Value;
            */
        }
Example #4
0
        public void Initialize(Stream stream)
        {
            _zipStream      = stream;
            _tempFolderName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ Guid.NewGuid().ToString()}");
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(_tempFolderName);

            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            FileInfo[] files = folder.GetFiles();

            FileInfo configFile = files.SingleOrDefault(p => p.Name == "plugin.json");

            if (configFile == null)
            {
                throw new MissingConfigurationFileException();
            }
            else
            {
                using (FileStream s = configFile.OpenRead())
                {
                    LoadConfiguration(s);
                }
            }
        }
Example #5
0
        public static void Compres(string path, IFormFile file, FType fType)
        {
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);

            using (var ms = new MemoryStream())
            {
                using (var archive =
                           new System.IO.Compression.ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    MemoryStream memoryStream = new MemoryStream();
                    file.OpenReadStream().CopyTo(memoryStream);
                    var    strearFile = file.OpenReadStream();
                    byte[] fileByte   = memoryStream.ToArray();

                    var zipEntry = archive.CreateEntry(file.FileName,
                                                       CompressionLevel.Optimal);
                    using (var zipStream = zipEntry.Open())
                    {
                        zipStream.Write(fileByte, 0, fileByte.Length);
                        zipStream.Close();
                        fs.Write(ms.ToArray());
                        fs.Close();
                    }

                    //var zipEntry2 = archive.CreateEntry("image2.png",
                    //    CompressionLevel.Fastest);
                    //using (var zipStream = zipEntry2.Open())
                    //{
                    //    zipStream.Write(bytes2, 0, bytes2.Length);
                    //}
                }
            }
        }
        private static Stream CreateTestPackageStream()
        {
            var packageStream = new MemoryStream();
            using (var packageArchive = new ZipArchive(packageStream, ZipArchiveMode.Create, true))
            {
                var nuspecEntry = packageArchive.CreateEntry("TestPackage.nuspec", CompressionLevel.Fastest);
                using (var streamWriter = new StreamWriter(nuspecEntry.Open()))
                {
                    streamWriter.WriteLine(@"<?xml version=""1.0""?>
                    <package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
                      <metadata>
                        <id>TestPackage</id>
                        <version>0.0.0.1</version>
                        <title>Package A</title>
                        <authors>ownera, ownerb</authors>
                        <owners>ownera, ownerb</owners>
                        <requireLicenseAcceptance>false</requireLicenseAcceptance>
                        <description>package A description.</description>
                        <language>en-US</language>
                        <projectUrl>http://www.nuget.org/</projectUrl>
                        <iconUrl>http://www.nuget.org/</iconUrl>
                        <licenseUrl>http://www.nuget.org/</licenseUrl>
                        <dependencies />
                      </metadata>
                    </package>");
                }

                packageArchive.CreateEntry("content\\HelloWorld.cs", CompressionLevel.Fastest);
            }

            packageStream.Position = 0;

            return packageStream;
        }
Example #7
0
        /// <summary>
        ///     Attempts to recompress an existing XAP file. If this results in a smaller file, it is replaced.
        /// </summary>
        /// <returns>true if file was succesfully recompressed.</returns>
        public Tuple<long, long> Recompress()
        {
            if (HasChanges)
            {
                throw new InvalidOperationException("Archive has pending changes. Save it first before attempting recompression.");
            }

            using (var ms = new MemoryStream())
            {
                using (var recompressed = new ZipArchive(ms, ZipArchiveMode.Create))
                {
                    CopyZipEntries(OutputArchive, recompressed, entry => true);
                }

                byte[] buffer = ms.ToArray();
                long existingLength = FileSystem.FileSize(OutputPath);

                if (buffer.Length < existingLength)
                {
                    Close();
                    FileSystem.FileWriteAllBytes(OutputPath, buffer);
                    Load();

                    return Tuple.Create(existingLength, buffer.LongLength);
                }

                return Tuple.Create(existingLength, existingLength);
            }
        }
Example #8
0
 private void ZipperAddFile(System.IO.Compression.ZipArchive zipper, dodSON.Core.FileStorage.ICompressedFileStoreItem item)
 {
     // create new zip item
     zipper.CreateEntryFromFile(item.OriginalFilename, item.RootFilename, (item.CompressionStrategy == CompressionStorageStrategy.Compress) ?
                                CompressionLevel.Optimal :
                                CompressionLevel.NoCompression);
 }
Example #9
0
        public void ReduceXap_CreateNewFile_Test()
        {
            var fileSystem = Substitute.For<IFileSystem>();
            var console = new StringWriter();

            CreateFakeInputXap(fileSystem, ZipArchiveMode.Read, "A", "B").
                AddResourceAssemblyPart("en", "A").
                AddResourceAssemblyPart("en-US", "A").
                AddResourceAssemblyPart("en", "B");

            CreateFakeSourceXap(fileSystem, "A", "C");

            MemoryStream outputStream = new MemoryStream();
            fileSystem.FileExists("Output.xap").Returns(true);
            fileSystem.OpenArchive("Output.xap", ZipArchiveMode.Create).Returns(new ZipArchive(outputStream, ZipArchiveMode.Create, true));

            var options = new Options()
            {
                Input = "Input.xap",
                Sources = new[] { "Source.xap" },
                Output = "Output.xap"
            };

            var builder = new XapBuilder();
            builder.AddAssemblyPart("A", 1000);

            var minifier = new XapMinifier(fileSystem, console);
            minifier.ReduceXap(options);

            var output = new ZipArchive(outputStream, ZipArchiveMode.Read, true);
            Assert.AreEqual(3, output.Entries.Count);
            Assert.IsNotNull(output.GetEntry("B.dll"));
            Assert.IsNotNull(output.GetEntry("en\\B.resources.dll"));
        }
Example #10
0
        private async Task<bool> LoadAndInstall() {
            if (_isInstalling) return false;
            _isInstalling = true;

            try {
                var data = await CmApiProvider.GetDataAsync("data/latest");
                if (data == null) throw new InformativeException(ToolsStrings.AppUpdater_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks);

                string installedVersion = null;
                await Task.Run(() => {
                    var location = FilesStorage.Instance.Combine(FilesStorage.DataDirName);
                    Directory.Delete(location, true);

                    using (var stream = new MemoryStream(data, false))
                    using (var archive = new ZipArchive(stream)) {
                        installedVersion = VersionFromData(archive.GetEntry(@"Manifest.json").Open().ReadAsStringAndDispose());
                        archive.ExtractToDirectory(location);
                    }
                });

                InstalledVersion = installedVersion;
                Logging.Write("Data loaded: " + InstalledVersion);
                return true;
            } catch (Exception e) {
                NonfatalError.Notify(ToolsStrings.ContentSyncronizer_CannotLoadContent, ToolsStrings.ContentSyncronizer_CannotLoadContent_Commentary, e);
            } finally {
                _isInstalling = false;
            }

            return false;
        }
        public void Initialize(Stream stream)
        {
            _zipStream      = stream;
            _tempFolderName = $"{ AppDomain.CurrentDomain.BaseDirectory }{ Guid.NewGuid().ToString()}";
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(_tempFolderName);

            var folder = new DirectoryInfo(_tempFolderName);

            var files = folder.GetFiles();

            var configFiles = files.Where(p => p.Name == "plugin.json");

            if (!configFiles.Any())
            {
                throw new Exception("The plugin is missing the configuration file.");
            }
            else
            {
                using (var s = configFiles.First().OpenRead())
                {
                    LoadConfiguration(s);
                }
            }
        }
        private static string AddToArchive(string entryName, Stream inputStream, ZipArchive zipArchive, string hashName)
        {
            var entry = zipArchive.CreateEntry(entryName);

            HashAlgorithm hashAlgorithm = null;
            BinaryWriter zipEntryWriter = null;
            try
            {
                hashAlgorithm = HashAlgorithm.Create(hashName);
                zipEntryWriter = new BinaryWriter(entry.Open());

                var readBuffer = new byte[StreamReadBufferSize];
                int bytesRead;
                while ((bytesRead = inputStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    zipEntryWriter.Write(readBuffer, 0, bytesRead);
                    hashAlgorithm.TransformBlock(readBuffer, 0, bytesRead, readBuffer, 0);
                }
                hashAlgorithm.TransformFinalBlock(readBuffer, 0, 0);

                var hashHexStringBuilder = new StringBuilder();
                foreach (byte hashByte in hashAlgorithm.Hash)
                {
                    hashHexStringBuilder.Append(hashByte.ToString("x2"));
                }

                return hashHexStringBuilder.ToString();
            }
            finally
            {
                hashAlgorithm.SafeDispose();
                zipEntryWriter.SafeDispose();
            }
        }
Example #13
0
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="dirPath">要解压到的路径</param>
        /// <param name="input">压缩文件数据</param>
        internal static void UnZippingFiles(string dirPath, byte[] input)
        {
            //备份文件到dirPath下Backup文件夹下
            ZippingBackupFiles(dirPath, dirPath + "Backup\\");
            //覆盖文件
            using (var zipStream = new MemoryStream(input))//将压缩文件信息初始化到内存流
            {
                using (var source = new ZipArchive(zipStream, ZipArchiveMode.Read))//读取压缩文件
                {
                    foreach (var entry in source.Entries)
                    {
                        var fullPath = Path.GetFullPath(dirPath + entry.FullName);
                        if (fullPath.EndsWith("\\"))
                        {
                            if (!Directory.Exists(fullPath))
                            {
                                Directory.CreateDirectory(fullPath);
                            }
                        }
                        else
                        {
                            using (var stream = entry.Open())
                            {
                                using (FileStream fileStream = File.Open(fullPath, FileMode.Create))
                                {
                                    stream.CopyTo(fileStream);
                                }
                            }
                        }
                    }

                }
            }
        }
Example #14
0
        private Dictionary<string, XmlDocument> GetSimpleGetXmlDocuments(ZipArchive zip, string startsWith)
        {
            var Result = new Dictionary<string, XmlDocument>();

            var ZAEs = zip.Entries.Where(x => (x.FullName.StartsWith("data/" + startsWith) || x.FullName.StartsWith(startsWith)) && (Path.GetExtension(x.Name) == ".xml"));
            foreach (var ZAE in ZAEs)
            {
                // Open the file for reading
                using (var InStream = ZAE.Open())
                {
                    // Read each byte and convert to xml string
                    var InBytes = new List<byte>();
                    while (true)
                    {
                        var InByte = InStream.ReadByte();
                        if (InByte == -1) break;
                        InBytes.Add((byte)InByte);
                    }

                    // Parse the xml string
                    XmlDocument XmlDoc = new XmlDocument();
                    XmlDoc.LoadXml(Encoding.UTF8.GetString(InBytes.ToArray()));
                    Result.Add(ZAE.FullName, XmlDoc);
                }
            }

            return Result;
        }
Example #15
0
        public string[] ExtractEntries(string sourceArchiveFileName, string destinationDirectoryName)
        {
            using (var archiveStream = _fileSystem.OpenFile(sourceArchiveFileName, FileMode.Open, FileAccess.Read))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read))
            {
                foreach (var entry in archive.Entries)
                {
                    var path = PathHelper.Combine(destinationDirectoryName, entry.FullName);
                    if (string.IsNullOrEmpty(entry.Name))
                    {
                        // is a directory
                        if (!_fileSystem.DirExists(path))
                            _fileSystem.CreateDir(path);
                        continue;
                    }
                    else
                    {
                        var dir = PathHelper.GetParent(path);
                        if (!_fileSystem.DirExists(dir))
                            _fileSystem.CreateDir(dir);
                    }

                    using (var entryStream = entry.Open())
                    {
                        using (var fileStream = _fileSystem.OpenFile(path, FileMode.Create, FileAccess.Write))
                        {
                            entryStream.CopyTo(fileStream);
                            fileStream.Flush();
                        }
                    }
                }
                var entries = archive.Entries.Select(x => x.FullName).ToArray();
                return entries;
            }
        }
Example #16
0
        public void ReadExcelData(Stream excelfile)
        {
            //excelfile = Assembly.Load(new AssemblyName("ExcelManager")).GetManifestResourceStream(@"ExcelManager.Resources.ExcelTemplateFile.xlsx");
            System.IO.Compression.ZipArchive zipArchiveExcelTemplate = new System.IO.Compression.ZipArchive(excelfile);

            foreach (var file in zipArchiveExcelTemplate.Entries)
            {
                if (file.FullName == "xl/sharedStrings.xml")
                {
                    var s        = file.Open();
                    var xdoc     = XDocument.Load(s);
                    var xelement = XElement.Parse(xdoc.ToString());
                    var sst      = Deserialize <sst>(xelement.ToString());
                }
                else if (file.FullName == "xl/worksheets/sheet1.xml")
                {
                    var s         = file.Open();
                    var xdoc      = XDocument.Load(s);
                    var xelement  = XElement.Parse(xdoc.ToString());
                    var worksheet = Deserialize <worksheet>(xelement.ToString());
                }
                else if (file.FullName == "xl/styles.xml")
                {
                    //parsing cant be done as of now
                }
                else
                {
                }
            }
        }
Example #17
0
 /// <summary>
 /// 压缩更新文件
 /// </summary>
 /// <param name="dirInfo">需要更新文件目录</param>
 /// <param name="output"></param>
 /// <returns>压缩文件流</returns>
 internal static void ZippingFiles(string dirInfo, Stream output)
 {
     using (var archive = new ZipArchive(output, ZipArchiveMode.Create))
     {
         ZipInternalIteration(archive, dirInfo);
     }
 }
        public static void ZipRecursive(
            string rootDirectoryPath,
            DirectoryInfo currentDirectoryInfo, 
            ZipArchive archive, 
            TextWriter hashWriter, 
            string hashName = ConstDefaultHashName)
        {
            rootDirectoryPath = NormalizePath(rootDirectoryPath);
            foreach (var file in currentDirectoryInfo.GetFiles())
            {
                var entryName = file.FullName.Substring(rootDirectoryPath.Length);

                using (var reader = file.OpenRead())
                {
                    var hash = AddToArchive(entryName, reader, archive, hashName);
                    hashWriter.WriteLine(HashEntryFormat, hash, entryName);
                    Serilog.Log.Verbose("Added {filePath} to zip archive.  MD5: {md5}", file.FullName, hash);
                }
            }

            // recurse
            foreach (var directory in currentDirectoryInfo.GetDirectories())
            {
                ZipRecursive(rootDirectoryPath, directory, archive, hashWriter, hashName);
            }
        }
        public BitmapImage Convert([CanBeNull] string id) {
            if (id == null) id = @"_";

            BitmapImage bi;
            if (Cache.TryGetValue(id, out bi)) return bi;

            if (_archive == null) {
                _archive = new ZipArchive(new MemoryStream(BinaryResources.Flags));
            }

            var entryStream = (_archive.GetEntry(id) ?? _archive.GetEntry(@"_"))?.Open();
            if (entryStream == null) {
                return null;
            }

            bi = new BitmapImage();
            bi.BeginInit();
            bi.CacheOption = BitmapCacheOption.OnLoad;
            bi.StreamSource = entryStream.ReadAsMemoryStream();
            bi.EndInit();
            bi.Freeze();

            Cache[id] = bi;
            return bi;
        }
        public void AddDirectoryToArchiveIncludesDirectoryTreeInArchive()
        {
            // Arrange
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create);

            var emptyDir = new Mock<DirectoryInfoBase>();
            emptyDir.SetupGet(d => d.Name).Returns("empty-dir");
            emptyDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[0]);
            var subDir = new Mock<DirectoryInfoBase>();
            subDir.SetupGet(d => d.Name).Returns("site");
            subDir.Setup(d => d.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { emptyDir.Object, CreateFile("home.aspx", "home content"), CreateFile("site.css", "some css") });

            var directoryInfo = new Mock<DirectoryInfoBase>();
            directoryInfo.SetupGet(f => f.Name).Returns("zip-test");
            directoryInfo.Setup(f => f.GetFileSystemInfos()).Returns(new FileSystemInfoBase[] { subDir.Object, CreateFile("zero-length-file", ""), CreateFile("log.txt", "log content") });

            // Act
            zip.AddDirectory(directoryInfo.Object, "");

            // Assert
            zip.Dispose();
            File.WriteAllBytes(@"d:\foo.zip", stream.ToArray());
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(5, zip.Entries.Count);
            AssertZipEntry(zip, "log.txt", "log content");
            AssertZipEntry(zip, @"site\home.aspx", "home content");
            AssertZipEntry(zip, @"site\site.css", "some css");
            AssertZipEntry(zip, @"site\empty-dir\", null);
            AssertZipEntry(zip, @"zero-length-file", null);
        }
Example #21
0
    private void Zip(AbsolutePath target, IEnumerable <string> paths)
    {
        var  targetPath = target.ToString();
        bool finished = false, atLeastOneFileAdded = false;

        try
        {
            using (var targetStream = File.Create(targetPath))
                using (var archive = new System.IO.Compression.ZipArchive(targetStream, ZipArchiveMode.Create))
                {
                    void AddFile(string path, string relativePath)
                    {
                        var e = archive.CreateEntry(relativePath.Replace("\\", "/"), CompressionLevel.Optimal);

                        using (var entryStream = e.Open())
                            using (var fileStream = File.OpenRead(path))
                                fileStream.CopyTo(entryStream);
                        atLeastOneFileAdded = true;
                    }

                    foreach (var path in paths)
                    {
                        if (Directory.Exists(path))
                        {
                            var dirInfo  = new DirectoryInfo(path);
                            var rootPath = Path.GetDirectoryName(dirInfo.FullName);
                            foreach (var fsEntry in dirInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                            {
                                if (fsEntry is FileInfo)
                                {
                                    var relPath = Path.GetRelativePath(rootPath, fsEntry.FullName);
                                    AddFile(fsEntry.FullName, relPath);
                                }
                            }
                        }
                        else if (File.Exists(path))
                        {
                            var name = Path.GetFileName(path);
                            AddFile(path, name);
                        }
                    }
                }

            finished = true;
        }
        finally
        {
            try
            {
                if (!finished || !atLeastOneFileAdded)
                {
                    File.Delete(targetPath);
                }
            }
            catch
            {
                //Ignore
            }
        }
    }
Example #22
0
        public static ZipFileMock Archive(string sourceDirectoryName, string destinationArchiveFileName, params FileMock[] files)
        {
            var bytes = new byte[0];
            using (var stream = new MemoryStream())
            {
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
                {
                    foreach (var file in files)
                    {
                        var relativePath = PathHelper.Subtract(file.Path, sourceDirectoryName);
                        var entry = archive.CreateEntry(relativePath);

                        using (var entryStream = entry.Open())
                        {
                            entryStream.Write(file.Bytes, 0, file.Bytes.Length);
                            entryStream.Flush();
                        }
                    }
                }

                // Fix for "invalid zip archive"
                using ( var fileStream = new MemoryStream() )
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.CopyTo(fileStream);
                    bytes = fileStream.ToArray();
                }
            }

            var zipFile = new ZipFileMock(destinationArchiveFileName, bytes, files);
            return zipFile;
        }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelInfo"/> class.
        /// </summary>
        /// <param name="fileInfo">The model file info.</param>
        /// <exception cref="System.ArgumentNullException">fileInfo</exception>
        /// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
        /// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
        public ModelInfo(FileInfo fileInfo) {
            if (fileInfo == null)
                throw new ArgumentNullException("fileInfo");

            if (!fileInfo.Exists)
                throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);

            File = fileInfo;
            Name = Path.GetFileNameWithoutExtension(fileInfo.Name);

            try {

                using (var zip = new ZipArchive(fileInfo.OpenRead(), ZipArchiveMode.Read)) {
                    foreach (var entry in zip.Entries) {
                        if (entry.Name != ArtifactProvider.ManifestEntry) 
                            continue;

                        using (var stream = entry.Open()) {
                            Manifest = (Properties)Properties.Deserialize(stream);
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                throw new InvalidFormatException("Unable to load the specified model file.", ex);
            }
        }
        public ICollection<KeyValuePair<string, Stream>> DecompressMessage(Stream inputStream)
        {
            var messageParts = new List<KeyValuePair<string, Stream>>();

            using (ZipArchive zipArchive = new ZipArchive(inputStream, ZipArchiveMode.Read))
            {
                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                {
                    MemoryStream entryStream = new MemoryStream();
                    byte[] entrybuffer = new Byte[1024];
                    int entryBytesRead = 1024;
                    Stream zipArchiveEntryStream = entry.Open();
                    while (entryBytesRead != 0)
                    {
                        entryBytesRead = zipArchiveEntryStream.Read(entrybuffer, 0, entrybuffer.Length);
                        entryStream.Write(entrybuffer, 0, entryBytesRead);
                    }

                    entryStream.Position = 0;
                    messageParts.Add(new KeyValuePair<string, Stream>(entry.Name, entryStream));
                }
            }

            return messageParts;
        }
Example #25
0
        async public static Task UnZipFile(StorageFolder zipFileDirectory, string zipFilename, StorageFolder extractFolder = null)
        {
            if (extractFolder == null) extractFolder = zipFileDirectory;

            var folder = ApplicationData.Current.LocalFolder;

            using (var zipStream = await folder.OpenStreamForReadAsync(zipFilename))
            {
                using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length))
                {
                    await zipStream.CopyToAsync(zipMemoryStream);

                    using (var archive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read))
                    {
                        foreach (ZipArchiveEntry entry in archive.Entries)
                        {
                            if (entry.Name != "")
                            {
                                using (Stream fileData = entry.Open())
                                {
                                    StorageFile outputFile = await extractFolder.CreateFileAsync(entry.FullName, CreationCollisionOption.ReplaceExisting);
                                    using (Stream outputFileStream = await outputFile.OpenStreamForWriteAsync())
                                    {
                                        await fileData.CopyToAsync(outputFileStream);
                                        await outputFileStream.FlushAsync();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #26
0
        /// <summary>
        /// Reads a GTFS zip archive stream and converts it into a <see cref="GtfsFeed"/>.
        /// </summary>
        /// <param name="stream">A zip archive <see cref="Stream"/> containing General Transit Feet Specification data.</param>
        /// <param name="options">
        /// Use this to specify which files you want to extract from the GTFS. Defaults to <see cref="GtfsFileOptions.All"/>.
        /// You should specify this parameter if you know that you will only need certain tables out of the GTFS.
        /// </param>
        /// <returns>A <see cref="GtfsFeed"/> representation of the contents of <paramref name="stream"/>.</returns>
        public static async Task <GtfsFeed> ReadGtfsAsync(this Stream stream, GtfsFileOptions options = GtfsFileOptions.All)
        {
            if (options == GtfsFileOptions.None)
            {
                throw new ArgumentException("The \"options\" parameter cannot be \"None\".");
            }

            GtfsFeed feed;

            using (var zip = new System.IO.Compression.ZipArchive(stream, ZipArchiveMode.Read, false))
            {
                feed = new GtfsFeed
                {
                    Agency         = options.HasFlag(GtfsFileOptions.Agency) ? await zip.ParseCsv <Agency>("agency.txt", true) : null,
                    Stops          = options.HasFlag(GtfsFileOptions.Stops) ? (await zip.ParseCsv <Stop>("stops.txt", true)).ToFeatureCollection() : null,
                    Routes         = options.HasFlag(GtfsFileOptions.Routes) ? await zip.ParseCsv <Route>("routes.txt", true) : null,
                    Trips          = options.HasFlag(GtfsFileOptions.Trips) ? await zip.ParseCsv <Trip>("trips.txt", true) : null,
                    StopTimes      = options.HasFlag(GtfsFileOptions.StopTimes) ? await zip.ParseCsv <StopTime>("stop_times.txt", true) : null,
                    Calendar       = options.HasFlag(GtfsFileOptions.Calendar) ? await zip.ParseCsv <Calendar>("calendar.txt", true) : null,
                    CalendarDates  = options.HasFlag(GtfsFileOptions.CalendarDates) ? await zip.ParseCsv <CalendarDate>("calendar_dates.txt") : null,
                    FareAttributes = options.HasFlag(GtfsFileOptions.FareAttributes) ? await zip.ParseCsv <FareAttribute>("fare_attributes.txt") : null,
                    FareRules      = options.HasFlag(GtfsFileOptions.FareRules) ? await zip.ParseCsv <FareRule>("fare_rules.txt") : null,
                    Shapes         = options.HasFlag(GtfsFileOptions.Shapes) ? (await zip.ParseCsv <Shape>("shapes.txt")).ToFeatureCollection() : null,
                    Frequencies    = options.HasFlag(GtfsFileOptions.Frequencies) ? await zip.ParseCsv <Frequency>("frequencies.txt") : null,
                    Transfers      = options.HasFlag(GtfsFileOptions.Transfers) ? await zip.ParseCsv <Transfer>("transfers.txt") : null
                };

                var feedInfo = options.HasFlag(GtfsFileOptions.FeedInfo) ? await zip.ParseCsv <FeedInfo>("feed_info.txt") : null;

                feed.FeedInfo = feedInfo != null?feedInfo.FirstOrDefault() : null;
            }

            return(feed);
        }
 public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
   List<ResourceRegressionDataDescriptor> descriptorList = new List<ResourceRegressionDataDescriptor>();
   descriptorList.Add(new ChemicalOne());
   descriptorList.Add(new Housing());
   descriptorList.Add(new Tower());
   descriptorList.Add(new Powermeter());
   var solutionsArchiveName = GetResourceName(FileName + @"\.zip");
   if (!String.IsNullOrEmpty(solutionsArchiveName)) {
     using (var solutionsZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(solutionsArchiveName), ZipArchiveMode.Read)) {
       IList<string> entries = new List<string>();
       foreach (var curEntry in solutionsZipFile.Entries) {
         entries.Add(curEntry.Name);
       }
       foreach (var entry in entries.OrderBy(x => x)) {
         string prettyName = Path.GetFileNameWithoutExtension(entry);
         ResourceRegressionDataDescriptor desc = descriptorList.Where(x => x.Name.Equals(prettyName)).FirstOrDefault();
         if (desc != null) {
           desc.ResourceName = entry;
           yield return desc;
         } else
           throw new ArgumentNullException("No Descriptor could be found for this entry.");
       }
     }
   }
 }
Example #28
0
        public void SaveDialogData(string fileLocation, IDialog graphInstance, FileCopy customCopy = null)
        {
            // copy current zip and then write json data in
            reWriteRecord(JsonRecordName, Encoding.Unicode.GetBytes(graphInstance.Json));
            FlushReopen();

            linkedArchive.Dispose();
            linkedArchive = null;
            baseStream.Close();
            try
            {
                //File.Move(FileName, fileLocation);
                //LinkFile(fileLocation);
                if (customCopy == null)
                {
                    File.Copy(FileName, fileLocation, true);
                }
                else
                {
                    customCopy(FileName, fileLocation);// optional encoding
                }
                LinkFile(FileName);
            }
            catch (Exception exc)
            {
                System.Windows.Forms.MessageBox.Show("Error while savings: " + exc.Message);
                LinkFile(FileName);
            }
        }
        public async override Task<bool> InstallPackageAsync(Packaging.Core.PackageIdentity packageIdentity, System.IO.Stream packageStream,
            INuGetProjectContext nuGetProjectContext, CancellationToken token)
        {
            if (!packageStream.CanSeek)
            {
                throw new ArgumentException(NuGet.ProjectManagement.Strings.PackageStreamShouldBeSeekable);
            }

            nuGetProjectContext.Log(MessageLevel.Info, Strings.InstallingPackage, packageIdentity);

            packageStream.Seek(0, SeekOrigin.Begin);
            var zipArchive = new ZipArchive(packageStream);
            PackageReader packageReader = new PackageReader(zipArchive);
            var packageSupportedFrameworks = packageReader.GetSupportedFrameworks();
            var projectFrameworks = _project.GetSupportedFrameworksAsync(token)
                .Result
                .Select(f => NuGetFramework.Parse(f.FullName));

            var args = new Dictionary<string, object>();
            args["Frameworks"] = projectFrameworks.Where(
                projectFramework =>
                    IsCompatible(projectFramework, packageSupportedFrameworks)).ToArray();
            await _project.InstallPackageAsync(
                new NuGetPackageMoniker
                {
                    Id = packageIdentity.Id,
                    Version = packageIdentity.Version.ToNormalizedString()
                },
                args,
                logger: null,
                progress: null,
                cancellationToken: token);
            return true;
        }
        public async Task <MemoryStream> GenerateZip(string report, string log)
        {
            using var ms      = new MemoryStream();
            using var archive =
                      new System.IO.Compression.ZipArchive(ms, ZipArchiveMode.Create, true);
            byte[] reportBytes = Encoding.ASCII.GetBytes(report);
            byte[] logBytes    = Encoding.ASCII.GetBytes(log);

            var zipEntry = archive.CreateEntry("Report.trx",
                                               CompressionLevel.Fastest);

            using (var zipStream = zipEntry.Open())
            {
                await zipStream.WriteAsync(reportBytes, 0, reportBytes.Length).ConfigureAwait(false);
            }

            var zipEntry2 = archive.CreateEntry("log.txt",
                                                CompressionLevel.Fastest);

            using (var zipStream = zipEntry2.Open())
            {
                await zipStream.WriteAsync(logBytes, 0, logBytes.Length).ConfigureAwait(false);
            }
            return(ms);
        }
Example #31
0
        static void ProcessFolder(XElement folder, ZipArchive theZip, string folderRelativePath)
        {
            string targetDirectory = (string)folder.Attribute("Name");
            string currentRelativePath = AppendRelativePath(folderRelativePath, targetDirectory);

            Console.WriteLine("Processing folder " + currentRelativePath);

            foreach (var component in folder.Elements(Namespace + ElementNameComponent))
            {
                foreach (var file in component.Elements(Namespace + ElementNameFile))
                {
                    string source = (string)file.Attribute("Source");
                    string name = (string)file.Attribute("Name");

                    theZip.CreateEntryFromFile(RelativePathToolToSetupFolder + source,
                        AppendRelativePath(currentRelativePath, name),
                        CompressionLevel.Optimal);
                }
            }

            foreach (var secondaryFolder in folder.Elements(Namespace + ElementNameDirectory))
            {
                ProcessFolder(secondaryFolder, theZip, currentRelativePath);
            }
        }
        public void Initialize(Stream stream)
        {
            _zipStream      = stream;
            _tempFolderName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ Guid.NewGuid().ToString()}");
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            archive.ExtractToDirectory(_tempFolderName);

            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            FileInfo[] files = folder.GetFiles();
            var        entryAssemblyFileName = Path.GetFileNameWithoutExtension(_packagePath).ToLower() + ".dll";
            FileInfo   configFile            = files.SingleOrDefault(p => p.Name.ToLower() == entryAssemblyFileName);

            if (configFile == null)
            {
                throw new QStack.Framework.Core.ServiceFrameworkException("can not find the entry assembly.the package name must be same as the entry assembly.");
            }
            else
            {
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(configFile.FullName);

                _pluginInfo = new PluginInfoDto
                {
                    DisplayName = fileVersionInfo.FileDescription,
                    Version     = fileVersionInfo.FileVersion,
                    Name        = Path.GetFileNameWithoutExtension(fileVersionInfo.FileName)
                };
            }
        }
		private async void ButtonRestore_Click(object sender, RoutedEventArgs e)
		{
			var selected = ListBoxBackups.SelectedItem as BackupFile;
			if(selected != null)
			{
				var result =
					await
					Helper.MainWindow.ShowMessageAsync("Restore backup " + selected.DisplayName,
					                                   "This can not be undone! Make sure you have a current backup (if necessary). To create one, CANCEL and click \"CREATE NEW\".",
					                                   MessageDialogStyle.AffirmativeAndNegative);
				if(result == MessageDialogResult.Affirmative)
				{
					var archive = new ZipArchive(selected.FileInfo.OpenRead(), ZipArchiveMode.Read);
					archive.ExtractToDirectory(Config.Instance.DataDir, true);
					Config.Load();
					Config.Save();
					DeckList.Load();
					DeckList.Save();
					DeckStatsList.Load();
					DeckStatsList.Save();
					DefaultDeckStats.Load();
					DefaultDeckStats.Save();
					Helper.MainWindow.ShowMessage("Success", "Please restart HDT for this to take effect.");
				}
			}
		}
Example #34
0
        public ActionResult GetSimple(HttpPostedFileBase file)
        {
            if ((file == null) || (file.ContentLength <= 0))
            {
                // TODO Display an error
            }
            else
            {
                try
                {
                    using (var DB = new XenonCMSContext())
                    {
                        using (var Zip = new ZipArchive(file.InputStream))
                        {
                            HandleGetSimpleBootstrap3SettingsXml(Zip, DB);
                            HandleGetSimpleNewsManagerPosts(Zip, DB);
                            HandleGetSimplePages(Zip, DB);
                            HandleGetSimpleWebsiteXml(Zip, DB);
                        }
                    }
                }
                catch (Exception ex)
                {
                    // TODO Archive is likely invalid?
                }
            }

            return View();
        }
Example #35
0
        private void ImportFiles(ZipArchive file, string path)
        {
            var enumerable = file.Entries.Where(a => a.FullName.StartsWith("data/"));

            foreach (var zipArchiveEntry in enumerable)
            {
                var directoryName = Path.GetDirectoryName(zipArchiveEntry.FullName);
                if (directoryName != null)
                {
                    string virtualPath = "." +
                                         (directoryName.Replace("\\", "/") + "/" +
                                          Path.GetFileNameWithoutExtension(zipArchiveEntry.FullName)).Substring(4);
                    var extension = Path.GetExtension(zipArchiveEntry.FullName);
                    if (extension != null && !Root.Information.DeletedFiles.Contains(virtualPath))
                    {
                        string hash = extension.Substring(1);

                        if (Root.Children.All(a => a.VirtualPath != virtualPath))
                            Root.Children.Add(new BackupFile
                                                  {
                                                      Name =
                                                          Path.GetFileNameWithoutExtension(
                                                              Path.GetFileName(zipArchiveEntry.FullName)),
                                                      FileHash = hash,
                                                      VirtualPath = virtualPath,
                                                      ArchivePath = path
                                                  });
                    }
                }
            }
        }
Example #36
0
        public void Load(ZipArchive iArchive)
        {
            JObject pJOtImages = null;
            ZipArchiveEntry pZAEImages = iArchive.GetEntry("images.json");
            if (pZAEImages != null)
            {
                using (Stream pStmImages = pZAEImages.Open())
                {
                    using (StreamReader pSRrReader = new StreamReader(pStmImages, Encoding.UTF8, false, 1024, true))
                    {
                        using (JsonTextReader pJTRReader = new JsonTextReader(pSRrReader))
                        {
                            pJOtImages = JObject.Load(pJTRReader);
                        }
                    }
                }
            }

            JArray pJAyImages = pJOtImages["images"].Value<JArray>(); ;
            foreach(JObject curImage in pJAyImages)
            {
                ProjectImage pPIeImage = ProjectImage.FromJSON(curImage);
                ZipArchiveEntry pZAEImage = iArchive.GetEntry(pPIeImage.ID);
                if (pZAEImage != null)
                {
                    using (Stream pStmImage = pZAEImage.Open())
                    {
                        pPIeImage.Image = Image.FromStream(pStmImage);
                        cDicImages.Add(pPIeImage.ID, pPIeImage);
                    }
                }
            }
        }
 /// <summary>
 /// Downloads the specified web driver version.
 /// </summary>
 /// <param name="version">The version to download.</param>
 protected override void Update(string version)
 {
     using (var client = new WebClient())
     using (var stream = client.OpenRead("http://chromedriver.storage.googleapis.com/" + version + "/chromedriver_win32.zip"))
     using (var archive = new ZipArchive(stream))
         archive.ExtractToDirectory(Path.Combine(ParentPath, version));
 }
        public void AddFileInUseTests()
        {
            // Arrange
            var fileName = @"x:\test\temp.txt";
            var exception = new IOException("file in use");
            var stream = new MemoryStream();
            var zip = new ZipArchive(stream, ZipArchiveMode.Create);
            var tracer = new Mock<ITracer>();
            var file = new Mock<FileInfoBase>();

            // setup
            file.Setup(f => f.OpenRead())
                .Throws(exception);
            file.SetupGet(f => f.FullName)
                .Returns(fileName);
            tracer.Setup(t => t.Trace(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()))
                  .Callback((string message, IDictionary<string, string> attributes) =>
                  {
                      Assert.Contains("error", attributes["type"]);
                      Assert.Contains(fileName, attributes["text"]);
                      Assert.Contains("file in use", attributes["text"]);
                  });

            // Act
            zip.AddFile(file.Object, tracer.Object, String.Empty);
            zip.Dispose();

            // Assert
            tracer.Verify(t => t.Trace(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>()), Times.Once());
            zip = new ZipArchive(ReOpen(stream));
            Assert.Equal(0, zip.Entries.Count);
        }
Example #39
0
        public void Restore(string slnFile)
        {
            using (var resourceStream = _fileSystem.OpenResource("slnRun.Resources.nuget.zip"))
            using (var zipFile = new ZipArchive(resourceStream))
            using (var nugetInputFile = zipFile.GetEntry("nuget.exe").Open())
            {
                var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                _fileSystem.CreateDirectory(tempPath);
                try
                {
                    var targetPath = Path.Combine(tempPath, "nuget.exe");
                    using (var nugetOutputFile = _fileSystem.CreateFile(targetPath))
                        nugetInputFile.CopyTo(nugetOutputFile);

                    var sb = new StringBuilder();
                    var exitCode = _processRunner.Run(targetPath, $"restore \"{slnFile}\"", x => { sb.Append(x); });
                    if (exitCode != 0)
                    {
                        _logger.Error(sb.ToString());
                        throw new SlnRunException("nuget package restore failed.");
                    }
                }
                finally
                {
                    _fileSystem.DeleteDirectory(tempPath);
                }
            }
        }
Example #40
0
        public override bool Execute()
        {
            if (SourceFiles == null && SourceDirectoryName == null)
            {
                Log.LogError(
                    $"{nameof (ZipArchive)}: either {nameof (SourceFiles)} or " +
                    $"{nameof (SourceDirectoryName)} must be provided.");
                return(false);
            }

            if (SourceFiles != null)
            {
                using (var stream = File.OpenWrite(DestinationArchiveFileName))
                    using (var archive = new SIOCZipArchive(stream, ZipArchiveMode.Create, true, Encoding.UTF8)) {
                        foreach (var item in SourceFiles)
                        {
                            var fullPath = item.GetMetadata("FullPath") ?? item.ItemSpec;
                            archive.CreateEntryFromFile(fullPath, item.ItemSpec);
                        }
                    }

                return(true);
            }

            if (!Directory.Exists(SourceDirectoryName))
            {
                throw new DirectoryNotFoundException(SourceDirectoryName);
            }

            var fullSourceDirectoryName = SourceDirectoryName.TrimEnd(
                Path.DirectorySeparatorChar,
                Path.AltDirectorySeparatorChar);

            var sourceDirectoryName = fullSourceDirectoryName;

            if (RenameBaseDirectoryTo != null)
            {
                sourceDirectoryName = Path.Combine(
                    Path.GetDirectoryName(fullSourceDirectoryName),
                    Path.GetFileName(RenameBaseDirectoryTo));

                Directory.Move(fullSourceDirectoryName, sourceDirectoryName);
            }

            Log.LogMessage(
                MessageImportance.High,
                "Creating archive: {0}",
                DestinationArchiveFileName);

            Directory.CreateDirectory(Path.GetDirectoryName(DestinationArchiveFileName));

            ZipFile.CreateFromDirectory(
                sourceDirectoryName,
                DestinationArchiveFileName,
                CompressionLevel.Optimal,
                includeBaseDirectory: true);

            return(true);
        }
Example #41
0
        public void FlushReopen()
        {
            linkedArchive.Dispose();
            linkedArchive = null;
            baseStream.Close();

            LinkFile(FileName);
        }
Example #42
0
 private static void ZipOutputs(HashSet <string> inputs, string output)
 {
     System.IO.Compression.ZipArchive outputs = ZipFile.Open(output, ZipArchiveMode.Create);
     foreach (var input in inputs)
     {
         outputs.CreateEntryFromFile(input, Path.GetFileName(input), CompressionLevel.Optimal);
     }
 }
        /// <summary>
        ///     Function to iterate archive and trigger extraction of a required file(s)
        /// </summary>
        /// <param name="archive"></param>
        /// <param name="bAdiOnly"></param>
        /// <param name="bIsUpdate"></param>
        private void ProcessArchive(System.IO.Compression.ZipArchive archive, bool bAdiOnly, bool bIsUpdate)
        {
            foreach (var entry in archive.Entries.OrderByDescending(e => e.Length))
            {
                if (AdiExtracted & IsLegacyGoPackage)
                {
                    break;
                }

                if (Path.GetExtension(entry.FullName) == ".stl")
                {
                    if (!StlExtracted)
                    {
                        Log.Info($"Extracting Subtitle file: {entry.Name}");
                        ExtractEntry(entry, "stl");
                    }
                }
                if (!AdiExtracted & IsLegacyGoPackage & entry.Name.ToLower().Equals("adi.xml"))
                {
                    Log.Info("Legacy go Package - Extracting ADI.xml Only");
                    ExtractEntry(entry, "adi");
                }
                else
                {
                    if (!AdiExtracted & entry.Name.ToLower().Equals("adi.xml"))
                    {
                        Log.Info("Extracting ADI File from archive.");
                        ExtractEntry(entry, "adi");
                    }
                    if (bAdiOnly)
                    {
                        continue;
                    }
                    if (!bIsUpdate)
                    {
                        if (!MovieAssetExtracted & entry.FullName.Contains("media/"))
                        {
                            Log.Info($"Extracting Largest .ts file: {entry.Name} from Package");
                            ExtractEntry(entry, "movie");
                        }

                        if (PreviewExtracted || !entry.FullName.Contains("preview/"))
                        {
                            continue;
                        }

                        Log.Info($"Extracting Largest Preview Asset {entry.Name} from Package.");
                        ExtractEntry(entry, "preview");
                    }
                    else if (PreviewOnly & entry.FullName.Contains("preview/") & !PreviewExtracted)
                    {
                        Log.Info($"Extracting Largest Preview Asset {entry.Name} from Package.");
                        ExtractEntry(entry, "preview");
                    }
                }
            }
        }
Example #44
0
 public void Dispose()
 {
     //Close();
     if (_zipArchive != null)
     {
         _zipArchive.Dispose();
         _zipArchive = null;
     }
 }
Example #45
0
        public static void Test_OpenXml_Zip_01(string docxFile, string directory, bool useSlash, bool addDirectoryEntry)
        {
            // ok    useSlash = false, addDirectoryEntry = false
            // bad   useSlash = false, addDirectoryEntry = true               le fichier est corrompu
            // ok    useSlash = true,  addDirectoryEntry = true
            // ok    useSlash = true,  addDirectoryEntry = false
            if (zFile.Exists(docxFile))
            {
                zFile.Delete(docxFile);
            }
            int l = directory.Length;

            if (!directory.EndsWith("\\"))
            {
                l++;
            }
            //using (FileStream fs = new FileStream(docxFile, FileMode.OpenOrCreate))
            using (FileStream fs = zFile.Open(docxFile, FileMode.OpenOrCreate))
                using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update, false, Encoding.UTF8))
                {
                    int fileCount      = 0;
                    int directoryCount = 0;
                    foreach (FileSystemInfo file in new DirectoryInfo(directory).EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories))
                    {
                        string entryName = file.FullName.Substring(l);
                        if (useSlash)
                        {
                            entryName = entryName.Replace('\\', '/');
                        }
                        if ((file.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            if (useSlash)
                            {
                                entryName = entryName + "/";
                            }
                            else
                            {
                                entryName = entryName + "\\";
                            }
                            if (addDirectoryEntry)
                            {
                                Trace.WriteLine($"add directory \"{entryName}\"");
                                ZipArchiveEntry entry = zipArchive.CreateEntry(entryName);
                                directoryCount++;
                            }
                        }
                        else
                        {
                            Trace.WriteLine($"add file      \"{entryName}\"");
                            zipArchive.CreateEntryFromFile(file.FullName, entryName);
                            fileCount++;
                        }
                    }
                    Trace.WriteLine($"total {fileCount + directoryCount} entries {fileCount} files {directoryCount} directories");
                }
        }
Example #46
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);
 }
 /*
  * We expect teh Zip archive to contain:
  * ddd.zip {ddd = south-offset declination, SCP=0, NCP=180
  *      ddd {directory}
  *          bddd0.acc   {accelerator files}
  *          bddd0.cat   {astrometric catalogue data}
  *          bddd1.acc   {accelerator files}
  *          bddd1.cat   {astrometric catalogue data}
  *          ...
  *          bddd9.acc   {accelerator files}
  *          bddd9.cat   {astrometric catalogue data}
  *          *.
  */
 private async Task ExtractOne(string zipName, string destinationDirectory)
 {
     await using (var zipStream = new FileStream(zipName, FileMode.Open))
     {
         var zip = new System.IO.Compression.ZipArchive(zipStream, ZipArchiveMode.Read);
         Console.WriteLine($"Extracting {zipName}, {zip.Entries.Count} entries");
         zip.ExtractToDirectory(destinationDirectory);
         Console.WriteLine($"Finished {zipName}");
     }
 }
Example #48
0
        private void ZipperRemoveFile(System.IO.Compression.ZipArchive zipper, dodSON.Core.FileStorage.IFileStoreItem item)
        {
            // find existing zip item
            var entry = zipper.Entries.FirstOrDefault((e) => { return(e.FullName.Equals(item.RootFilename, StringComparison.InvariantCultureIgnoreCase)); });

            if (entry != null)
            {
                entry.Delete();
            }
        }
Example #49
0
 /// <summary>
 /// Will finalize the adding, updating and removing of files from the .zip file.
 /// </summary>
 /// <param name="state">A reference to an initialized System.IO.Compression.ZipArchive object. This reference, created in the <see cref="Save_Startup(out object)"/> will be destroyed and set to null in this method.</param>
 protected override void Save_Shutdown(ref object state)
 {
     try
     {
         // save state (zipper)
         if (state != null)
         {
             if (this.Count == 0)
             {
                 // #### no files left; delete back end storage
                 // dispose of zipper --> closes and commits the zip file
                 DisposeOfZipper(ref state);
                 FileStorageHelper.DeleteFile(BackendStorageZipFilename);
             }
             else
             {
                 if (_BackendChanged)
                 {
                     // #### back end has changed; save zip and update compression information
                     // dispose of zipper --> closes and commits the zip file
                     DisposeOfZipper(ref state);
                     // create a NEW zipper
                     // use a stand-in variable for the lambda expression
                     System.IO.Compression.ZipArchive zipState = CreateZipper(System.IO.Compression.ZipArchiveMode.Read);
                     // set the 'ref' object to the NEW zipper
                     state = zipState;
                     // **** update all compression information
                     ForEach(item =>
                     {
                         // reinitialize all compressed/uncompressed values
                         var found = zipState.Entries.FirstOrDefault((zf) => { return(CleanFilenameString(zf.FullName).Equals(item.RootFilename, StringComparison.InvariantCultureIgnoreCase)); });
                         if (found != null)
                         {
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionValues(found.CompressedLength);
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionStrategy(NormalizeCompressionStrategy(found));
                         }
                         else
                         {
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionValues(0);
                             ((dodSON.Core.FileStorage.ICompressedFileStoreItemAdvanced)item).SetCompressionStrategy(CompressionStorageStrategy.Store);
                         }
                     });
                     // **** clear the lambda stand-in variable
                     zipState        = null;
                     _BackendChanged = false;
                 }
             }
         }
     }
     finally
     {
         // #### fail-safe
         DisposeOfZipper(ref state);
     }
 }
Example #50
0
        public override bool Execute()
        {
            if (!IOFile.Exists(File))
            {
                Log.LogError("'{0}' does not exist", File);
                return(false);
            }

            Directory.CreateDirectory(DestinationFolder);

            var backslashIsInvalidFileNameChar = Path.GetInvalidFileNameChars().Any(c => c == '\\');

            var output = new List <ITaskItem>();

            using (var stream = IOFile.OpenRead(File))
                using (var zip = new ZipArchiveStream(stream, ZipArchiveMode.Read))
                {
                    foreach (var entry in zip.Entries)
                    {
                        var entryPath = entry.FullName;

                        if (!backslashIsInvalidFileNameChar)
                        {
                            // On non-Windows platforms, a backslash is a valid file name character.
                            // In almost all cases, a backslash in the zip entry was unintentional due
                            // to misuse of ZipArchiveStream. This normalizes backslashes to forward slash
                            // so the backslash is treated as a directory separator.

                            if (entry.FullName.IndexOf('\\') >= 0)
                            {
                                // Normalize backslashes in zip entry.
                                entryPath = entry.FullName.Replace('\\', '/');
                            }
                        }

                        var fileDest = Path.Combine(DestinationFolder, entryPath);
                        var dirName  = Path.GetDirectoryName(fileDest);
                        Directory.CreateDirectory(dirName);

                        // Do not try to extract directories
                        if (Path.GetFileName(fileDest) != string.Empty)
                        {
                            entry.ExtractToFile(fileDest, Overwrite);
                            Log.LogMessage(MessageImportance.Low, "Extracted '{0}'", fileDest);
                            output.Add(new TaskItem(fileDest));
                        }
                    }
                }

            Log.LogMessage(MessageImportance.High, "Extracted {0} file(s) to '{1}'", output.Count, DestinationFolder);
            OutputFiles = output.ToArray();

            return(true);
        }
Example #51
0
 public static void Test_ZipArchive_AddFile_01(string zipFile, string file, string entryName, CompressionLevel compressionLevel = CompressionLevel.Optimal,
                                               FileMode fileMode = FileMode.OpenOrCreate)
 {
     using (FileStream fileStream = new FileStream(zipFile, fileMode))
     {
         using (System.IO.Compression.ZipArchive archive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update))
         {
             archive.CreateEntryFromFile(file, entryName, compressionLevel);
         }
     }
 }
 private static void AddIfExist(FileInfo file, ZipArchive zip)
 {
     if (file.Exists)
     {
         using var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
         var entry = zip.CreateEntry(file.Name);
         using var entryStream = entry.Open();
         stream.CopyTo(entryStream);
         //zip.CreateEntryFromFile(file.FullName, file.Name);
     }
 }
Example #53
0
        public async Task <ICookBook> LoadCookBookFromFileStream(Stream File, CancellationToken token)
        {
            if (File == null)
            {
                throw new IOException("Invalid path (Directory not found)");
            }
            var archive = new System.IO.Compression.ZipArchive(File);

            Mediamanger mm = new Mediamanger(archive, token);

            return(await CookBook.Load(mm, token));
        }
Example #54
0
            private async Task AsyncDecompress(string Source, string Destnation, bool IsOverwrite)
            {
                // 非同期処理
                await Task.Run(() => {
                    System.IO.Compression.ZipArchive Archive = null;

                    string FullPath = String.Empty;

                    try {
                        // ZIPアーカイブを取得
                        using (Archive = System.IO.Compression.ZipFile.Open(Source, System.IO.Compression.ZipArchiveMode.Update)) {
                            foreach (var Entry in Archive.Entries)
                            {
                                // 抽出先フルパス作成
                                FullPath = System.IO.Path.Combine(Destnation, Entry.FullName);

                                // ディレクトリかどうか。
                                if (System.String.IsNullOrEmpty(Entry.Name))
                                {
                                    // ディレクトリなら、階層を再現する。
                                    if (!System.IO.Directory.Exists(FullPath))
                                    {
                                        System.IO.Directory.CreateDirectory(FullPath);
                                    }
                                }
                                else
                                {
                                    // ファイルなら、そのまま抽出。
                                    if (IsOverwrite)
                                    {
                                        Entry.ExtractToFile(FullPath, true);
                                    }
                                    else
                                    if (!System.IO.File.Exists(FullPath))
                                    {
                                        Entry.ExtractToFile(FullPath, true);
                                    }
                                }
                            }
                        }

                        //System.IO.Compression.ZipFile.ExtractToDirectory(ArchiveFile, Directory);
                    } catch (System.Exception ex) {
                        this.MyOperator.Logger.WriteLine(ex.Message, eLogLevel.ERROR);
                    } finally{
                        Archive?.Dispose();
                    }

                    this.IsDiscompressed = true;
                }).ConfigureAwait(false);

                this.IsAsynchronous = false;
            }
Example #55
0
        public static void FixupAarClass(string filename, string artName)
        {
            using (var fileStream = new FileStream(filename, FileMode.Open))
                using (var zipArchive = new System.IO.Compression.ZipArchive(fileStream, ZipArchiveMode.Update, true))
                {
                    var entryNames = zipArchive.Entries.Select(zae => zae.FullName).ToList();

                    Console.WriteLine("Found {0} entries in {1}", entryNames.Count, filename);

                    foreach (var entryName in entryNames)
                    {
                        var newName = entryName;

                        // Open the old entry
                        var oldEntry = zipArchive.GetEntry(entryName);
                        // We are only re-adding non empty folders, otherwise we end up with a corrupt zip in mono
                        if (!string.IsNullOrEmpty(oldEntry.Name))
                        {
                            // UGLY WORKAROUND
                            // In the some of the native libraries, there exist multiple .aar files which have a libs/r-classes.jar file.
                            // In Xamarin.Android, there is a Task "CheckDuplicateJavaLibraries" which inspects jar files being pulled in from .aar files
                            // in assemblies to see if there exist any files with the same name but different content, and will throw an error if it finds any.
                            // However, for us, it is perfectly valid to have this scenario and we should not see an error.
                            var newFile = Path.GetFileName(newName);
                            var newDir  = Path.GetDirectoryName(newName);

                            if (newFile.StartsWith("r", StringComparison.InvariantCulture))
                            {
                                newName = newDir + "/" + "r-" + artName + ".jar";
                            }

                            Console.WriteLine("Renaming: {0} to {1}", entryName, newName);

                            // Create a new entry based on our new name
                            var newEntry = zipArchive.CreateEntry(newName);


                            // Copy file contents over if they exist
                            if (oldEntry.Length > 0)
                            {
                                using (var oldStream = oldEntry.Open())
                                    using (var newStream = newEntry.Open())
                                    {
                                        oldStream.CopyTo(newStream);
                                    }
                            }
                        }

                        // Delete the old entry regardless of if it's a folder or not
                        oldEntry.Delete();
                    }
                }
        }
Example #56
0
        public static Task <IHttpResponse> QueryByContentIdAsync(
            [QueryParameter(CheckFileName = true, Name = ContentIdPropertyName)] Guid contentId,
            [OptionalQueryParameter] int?width,
            [OptionalQueryParameter] int?height,
            [OptionalQueryParameter] bool?fill,
            [OptionalQueryParameter] string renderer,
            BytesResponse onRawResponse,
            ImageRawResponse onImageResponse,
            NotFoundResponse onNotFound,
            UnauthorizedResponse onUnauthorized)
        {
            var response = EastFive.Api.Azure.Content.FindContentByContentIdAsync(contentId,
                                                                                  (contentType, image) =>
            {
                if (renderer.HasBlackSpace())
                {
                    if (renderer.ToLower() == "unzip")
                    {
                        using (var compressedStream = new MemoryStream(image))
                            using (var zipStream = new System.IO.Compression.ZipArchive(compressedStream, ZipArchiveMode.Read))
                                using (var resultStream = new MemoryStream())
                                {
                                    var zipFile = zipStream.Entries.First();
                                    zipFile.Open().CopyTo(resultStream);
                                    var data = resultStream.ToArray();
                                    return(onRawResponse(data, contentType: "application/object", filename: zipFile.Name));
                                    //return request.CreateFileResponse(data, "application/object", filename: zipFile.Name);
                                }
                    }
                }

                //if (contentType.StartsWith("video", StringComparison.InvariantCultureIgnoreCase) &&
                //    (width.HasValue || height.HasValue || fill.HasValue))
                //{
                //    var videoPreviewImage = default(System.Drawing.Image); // Properties.Resources.video_preview;
                //    return request.CreateImageResponse(videoPreviewImage,
                //        width: width, height: height, fill: fill,
                //        filename: contentId.ToString("N"));
                //}
                return(onImageResponse(image,
                                       width: width, height: height, fill: fill,
                                       filename: contentId.ToString("N"),
                                       contentType: contentType));
                //return request.CreateImageResponse(image,
                //    width: width, height: height, fill: fill,
                //    filename: contentId.ToString("N"),
                //    contentType: contentType);
            },
                                                                                  () => onNotFound(),
                                                                                  () => onUnauthorized());

            return(response);
        }
Example #57
0
        /// <summary>
        /// Close opened or created archive and save changes.
        /// </summary>
        /// <remarks>
        /// This method is automatically called at the end of the script.
        /// </remarks>
        /// <returns>TRUE on success or FALSE on failure.</returns>
        public bool close()
        {
            if (!CheckInitialized())
            {
                return(false);
            }

            _archive.Dispose();
            _archive      = null;
            this.filename = string.Empty;

            return(true);
        }
Example #58
0
        public void SetupFolder()
        {
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            _zipStream.Position = 0;
            _folderName         = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules", $"{_pluginConfiguration.Name}");

            archive.ExtractToDirectory(_folderName, true);

            DirectoryInfo folder = new DirectoryInfo(_tempFolderName);

            folder.Delete(true);
        }
        public void SetupFolder()
        {
            ZipTool archive = new ZipTool(_zipStream, ZipArchiveMode.Read);

            _zipStream.Position = 0;
            _folderName         = $"{AppDomain.CurrentDomain.BaseDirectory}Modules\\{Configuration.Name}";

            archive.ExtractToDirectory(_folderName, true);

            var folder = new DirectoryInfo(_tempFolderName);

            folder.Delete(true);
        }
Example #60
-1
 public static PushStreamContent Create(string fileName, ITracer tracer, Action<ZipArchive> onZip)
 {
     var content = new PushStreamContent((outputStream, httpContent, transportContext) =>
     {
         using (tracer.Step("ZipStreamContent.OnZip"))
         {
             try
             {
                 using (var zip = new ZipArchive(new StreamWrapper(outputStream), ZipArchiveMode.Create, leaveOpen: false))
                 {
                     onZip(zip);
                 }
             }
             catch (Exception ex)
             {
                 tracer.TraceError(ex);
                 throw;
             }
         }
     });
     content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
     content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
     content.Headers.ContentDisposition.FileName = fileName;
     return content;
 }