Пример #1
0
        public static FirefoxProfile FromBase64String(string base64)
        {
            string text = FileUtilities.GenerateRandomTempDirectoryName("webdriver.{0}.duplicated");

            byte[] buffer = Convert.FromBase64String(base64);
            using (MemoryStream memoryStream = new MemoryStream(buffer))
            {
                using (ZipStorer zipStorer = ZipStorer.Open(memoryStream, FileAccess.Read))
                {
                    List <ZipStorer.ZipFileEntry> list = zipStorer.ReadCentralDirectory();
                    foreach (ZipStorer.ZipFileEntry current in list)
                    {
                        string path = current.FilenameInZip.Replace('/', Path.DirectorySeparatorChar);
                        string destinationFileName = Path.Combine(text, path);
                        zipStorer.ExtractFile(current, destinationFileName);
                    }
                }
            }
            return(new FirefoxProfile(text, true));
        }
Пример #2
0
        public Card[] ReadMSE(string mseset, bool repalceOld)
        {
            //解压所有文件
            using (ZipStorer zips = ZipStorer.Open(mseset, FileAccess.Read))
            {
                zips.EncodeUTF8 = true;
                List <ZipStorer.ZipFileEntry> files = zips.ReadCentralDir();
                int count = files.Count;
                int i     = 0;
                foreach (ZipStorer.ZipFileEntry file in files)
                {
                    worker.ReportProgress(i / count, string.Format("{0}/{1}", i, count));
                    string savefilename = MyPath.Combine(mseHelper.ImagePath, file.FilenameInZip);
                    zips.ExtractFile(file, savefilename);
                }
            }
            string setfile = MyPath.Combine(mseHelper.ImagePath, "set");

            return(mseHelper.ReadCards(setfile, repalceOld));
        }
Пример #3
0
        private void Load(Stream _stream)
        {
            if (_stream == null)
            {
                throw new InvalidOperationException("No Stream to load!");
            }

            using (ZipStorer zip = ZipStorer.Open(_stream, FileAccess.Read))
            {
                // Read the central directory collection
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    Stream _fileStream = new MemoryStream();
                    zip.ExtractFile(entry, _fileStream);
                    if (entry.FilenameInZip == "meta.xml")
                    {
                        _metaData = XDocument.Parse(StreamToString(_fileStream));
                    }
                    else if (entry.FilenameInZip == "META-INF\\manifest.xml" || entry.FilenameInZip == "META-INF/manifest.xml" || entry.FilenameInZip == "manifest.xml")
                    {
                        _manifestData = XDocument.Parse(StreamToString(_fileStream));
                    }
                    else if (entry.FilenameInZip == "content.xml")
                    {
                        _contentData = XDocument.Parse(StreamToString(_fileStream));
                    }
                    else if (entry.FilenameInZip.StartsWith("attachments"))
                    { //附件
                        byte[] buf = new byte[_fileStream.Length];
                        _fileStream.Position = 0;
                        int count = _fileStream.Read(buf, 0, buf.Length);
                        attachments.Add(entry.FilenameInZip, buf);
                    }

                    _fileStream.Close();
                }
                zip.Close();
            }
        }
Пример #4
0
        //ディレクトリをzipファイルに書き込む
        private static void WriteDirToZip(ZipStorer zip, DirectoryInfo srcDir, string pathInZip)
        {
            var files = srcDir.EnumerateFiles();

            files = files.Where(e => e.Name != "mimetype"); //mimetypeファイルを除く

            foreach (var file in files)
            {
                var ext = file.Extension;

                ZipStorer.Compression compression;
                //ファイル形式によって圧縮形式を変える
                switch (ext)
                {
                case "jpg":     //画像ファイルは圧縮しない(時間の無駄なので)
                case "JPEG":
                case "png":
                case "PNG":
                case "gif":
                case "GIF":
                    compression = ZipStorer.Compression.Store;
                    break;

                case "EPUB":
                case "epub":
                    continue;       //EPUBファイルは格納しない

                default:
                    compression = ZipStorer.Compression.Deflate;      //通常のファイルは圧縮する
                    break;
                }
                WriteFileToZip(zip, file, pathInZip + file.Name, compression);
            }
            //残りのディレクトリを再帰的に書き込む
            var dirs = srcDir.EnumerateDirectories();

            foreach (var dir in dirs)
            {
                WriteDirToZip(zip, dir, pathInZip + dir.Name + "/");
            }
        }
Пример #5
0
        static void DoBackup()
        {
            if (!Directory.Exists(DataBackupDirectory))
            {
                Directory.CreateDirectory(DataBackupDirectory);
            }
            string backupFileName = String.Format(BackupFileNameFormat, DateTime.Now);   // localized

            backupFileName = Path.Combine(DataBackupDirectory, backupFileName);
            using (FileStream fs = File.Create(backupFileName)) {
                using (ZipStorer backupZip = ZipStorer.Create(fs, "")) {
                    foreach (string dataFileName in FilesToBackup)
                    {
                        if (File.Exists(dataFileName))
                        {
                            backupZip.AddFile(ZipStorer.Compression.Deflate, dataFileName, dataFileName, "");
                        }
                    }
                }
            }
        }
        public void WriteObjectItem(Stream stream, Func <int, object> getItem)
        {
            DateTime zipTime = DateTime.Now;

            using (ZipStorer zipStorer = ZipStorer.Create(stream))
            {
                object item;
                int    i = 0;
                while ((item = getItem(i)) != null)
                {
                    using (MemoryStream unzipStraem = new MemoryStream())
                    {
                        base.WriteObject(unzipStraem, item);

                        unzipStraem.Position = 0;
                        zipStorer.AddStream(ZipStorer.Compression.Deflate, i.ToString(), unzipStraem, zipTime);
                    }
                    i++;
                }
            }
        }
Пример #7
0
        private static void Main()
        {
            FileInfo binaries = new FileInfo(BinariesFileName);

            if (binaries.Exists)
            {
                binaries.Delete();
            }

            using (ZipStorer zs = ZipStorer.Create(binaries.FullName, "")) {
                foreach (string file in FileList)
                {
                    FileInfo fi = new FileInfo(file);
                    if (!fi.Exists)
                    {
                        return; // abort if any of the files do not exist
                    }
                    zs.AddFile(ZipStorer.Compression.Deflate, fi.FullName, fi.Name, "");
                }
            }
        }
Пример #8
0
 private Boolean UnzipInstaller(String installerZipAddress)
 {
     try
     {
         var installerZip = ZipStorer.Open(installerZipAddress, FileAccess.Read);
         var zipDir       = installerZip.ReadCentralDir();
         foreach (var file in zipDir)
         {
             installerZip.ExtractFile(file,
                                      Path.Combine(_targetInstallFolder, file.FilenameInZip));
         }
         installerZip.Close();
         return(true);
     }
     catch (Exception e)
     {
         PowerPointLabs.Views.ErrorDialogWrapper.ShowDialog("Failed to install",
                                                            "An error occurred while installing PowerPointLabs", e);
     }
     return(false);
 }
Пример #9
0
        /// <summary>
        /// Converts a base64-encoded string into a <see cref="FirefoxProfile"/>.
        /// </summary>
        /// <param name="base64">The base64-encoded string containing the profile contents.</param>
        /// <returns>The constructed <see cref="FirefoxProfile"/>.</returns>
        public static FirefoxProfile FromBase64String(string base64)
        {
            string destinationDirectory = FileUtilities.GenerateRandomTempDirectoryName("webdriver.{0}.duplicated");

            byte[] zipContent = Convert.FromBase64String(base64);
            using (MemoryStream zipStream = new MemoryStream(zipContent))
            {
                using (ZipStorer profileZipArchive = ZipStorer.Open(zipStream, FileAccess.Read))
                {
                    List <ZipStorer.ZipFileEntry> entryList = profileZipArchive.ReadCentralDirectory();
                    foreach (ZipStorer.ZipFileEntry entry in entryList)
                    {
                        string fileName        = entry.FilenameInZip.Replace('/', Path.DirectorySeparatorChar);
                        string destinationFile = Path.Combine(destinationDirectory, fileName);
                        profileZipArchive.ExtractFile(entry, destinationFile);
                    }
                }
            }

            return(new FirefoxProfile(destinationDirectory, true));
        }
Пример #10
0
        private static Dictionary <string, byte[]> ExtractZipFromMemoryStream(Stream stream)
        {
            var zip = ZipStorer.Open(stream, FileAccess.Read);

            var dir = zip.ReadCentralDir();

            var files = new Dictionary <string, byte[]>();

            // Look for the desired file
            foreach (var entry in dir)
            {
                var fileBytes = new byte[0];
                zip.ExtractFile(entry, out fileBytes);

                files.Add(entry.ToString(), fileBytes);
            }

            zip.Close();

            return(files);
        }
Пример #11
0
        public void Test_Common()
        {
            Assert.Throws(typeof(ArgumentNullException), () => { ZipStorer.Open("", FileAccess.Read); });

            string fileName = TestStubs.GetTempFilePath("test.zip");

            using (ZipStorer zip = ZipStorer.Create(fileName, "test")) {
                using (MemoryStream csvStream = new MemoryStream(Encoding.ASCII.GetBytes(TestStubs.CSVData))) {
                    zip.AddStream(ZipStorer.Compression.Deflate, "csv_file.csv", csvStream, DateTime.Now, "");
                }

                Assert.Throws(typeof(InvalidOperationException), () => { zip.ReadCentralDir(); });

                ZipStorer xzip = null;
                Assert.Throws(typeof(ArgumentNullException), () => { xzip = ZipStorer.RemoveEntries(xzip, null); });
                Assert.Throws(typeof(ArgumentNullException), () => { xzip = ZipStorer.RemoveEntries(xzip, null); });
            }

            using (ZipStorer zip = ZipStorer.Open(fileName, FileAccess.Read)) {
                Assert.Throws(typeof(ArgumentNullException), () => { zip.FindFile(null); });

                ZipStorer.ZipFileEntry entry = zip.FindFile("invalid");
                Assert.IsNull(entry);

                entry = zip.FindFile("csv_file.csv");
                Assert.IsNotNull(entry);

                using (MemoryStream csvStream = new MemoryStream()) {
                    Assert.Throws(typeof(ArgumentNullException), () => { zip.ExtractStream(entry, null); });

                    zip.ExtractStream(entry, csvStream);

                    csvStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(csvStream, Encoding.ASCII)) {
                        string text = reader.ReadToEnd();
                        Assert.AreEqual(TestStubs.CSVData, text);
                    }
                }
            }
        }
Пример #12
0
        public void unzipFile(string archive_name)
        {
            // Open an existing zip file for reading
            ZipStorer zip = ZipStorer.Open(archive_name, FileAccess.Read);

            string local_filename = null;

            if (Path.GetExtension(archive_name) == ".zip") // remove .zip extention
            {
                local_filename = Path.GetFileName(archive_name.Substring(0, archive_name.Length - 4));
            }

            // Read the central directory collection
            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

            // Look for the desired file
            foreach (ZipStorer.ZipFileEntry entry in dir)
            {
                string zippedFilename = Path.GetFileName(entry.FilenameInZip);

                //Console.WriteLine("Unzip zippedFilename: {0}", zippedFilename);
                //Console.WriteLine("Unzip local_file: {0}", local_filename);

                if (!zippedFilename.Equals(local_filename, StringComparison.InvariantCultureIgnoreCase))
                {
                    Console.WriteLine("Unzip skipping file: {0}", zippedFilename);
                    continue;
                }

                zip.ExtractFile(entry, Path.Combine(Path.GetDirectoryName(archive_name), zippedFilename));

                if (zippedFilename == CFG_FILENAME)
                {
                    Console.WriteLine("Reloading config file ...");
                    loadConfigFile();
                }
            }

            zip.Dispose();
        }
Пример #13
0
        public static Action <List <XMindWriterContext> > ZipXMindFolder(string xmindFileName)
        {
            var xMindSettings    = XMindConfigurationCache.Configuration.XMindConfigCollection;
            var filesToZipLabels = new string[] {
                "output:definition:meta",
                "output:definition:manifest",
                "output:definition:content"
            };
            var fileNames  = filesToZipLabels.Select(label => xMindSettings[label]).ToList();
            var filesToZip = xMindSettings.GetSection("output:files")
                             .GetChildren().Where(
                x => fileNames
                .Contains(
                    x.GetChildren()
                    .Where(el => el.Key == "name").Select(el => el.Value).FirstOrDefault()
                    )
                )
                             .Select(x => (File: x["name"], Path: x["location"]))
                             .ToList();

            return(ctx =>
            {
                using (ZipStorer zip = ZipStorer.Create(Path.Combine(xMindSettings["output:base"], xmindFileName), string.Empty))
                {
                    foreach (var fileToken in filesToZip)
                    {
                        var fullPath = Path.Combine(
                            Environment.CurrentDirectory,
                            XMindConfigurationCache.Configuration.XMindConfigCollection["output:base"],
                            fileToken.Path,
                            fileToken.File
                            );
                        zip.AddFile(ZipStorer.Compression.Deflate, fullPath, fileToken.File, string.Empty);
                    }
                    // zip.AddFile(ZipStorer.Compression.Deflate, "META-INF\\manifest.xml", "manifest.xml", string.Empty);
                    // zip.AddFile(ZipStorer.Compression.Deflate, "meta.xml", "meta.xml", string.Empty);
                    // zip.AddFile(ZipStorer.Compression.Deflate, "content.xml", "content.xml", string.Empty);
                }
            });
        }
Пример #14
0
        protected void btImport(object sender, EventArgs e)
        {
            try
            {
                if (!FileUpload1.HasFile)
                {
                    return;
                }

                byte[] ba = FileUpload1.FileBytes;

                if (FileUpload1.FileName.ToLower().EndsWith(".zip"))
                {
                    MemoryStream ms1 = new MemoryStream(ba);
                    ZipStorer    zip = ZipStorer.Open(ms1, FileAccess.Read);
                    List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                    MemoryStream ms2 = new MemoryStream();
                    zip.ExtractFile(dir[0], ms2);
                    zip.Close();
                    ba = ms2.ToArray();
                }

                MemoryStream ms3 = new MemoryStream(ba);
                using (MySqlConnection conn = new MySqlConnection(txtConnString.Text))
                {
                    MySqlCommand cmd = new MySqlCommand();
                    MySqlBackup  mb  = new MySqlBackup(cmd);
                    cmd.Connection = conn;
                    conn.Open();
                    mb.ImportFromMemoryStream(ms3);
                }

                Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('Import completed.');</script>"));
            }
            catch (Exception ex)
            {
                lbError.Text    = ex.Message;
                lbError.Visible = true;
            }
        }
Пример #15
0
        public static void ArchiveEpub(string srcDirName, string dstFileName)
        {
            var srcDir = new DirectoryInfo(srcDirName);

            var files = srcDir.EnumerateFiles();        //ファイルを取得
            var dirs  = srcDir.EnumerateDirectories();  //ディレクトリを取得


            //mimetypeファイルを取得する
            var mimeTypeFile = files.FirstOrDefault(e => e.Name == "mimetype");

            //container.xmlファイルを取得する
            var metaInfDir       = dirs.First(e => e.Name == "META-INF");
            var containedFiles   = metaInfDir.EnumerateFiles();
            var containerXmlFile = containedFiles.FirstOrDefault(e => e.Name == "container.xml");

            if (mimeTypeFile == null)
            {
                MessageBox.Show("mimetypeファイルがありません");
            }
            else if (containerXmlFile == null)
            {
                MessageBox.Show("container.xmlファイルがありません");
            }
            else
            {
                //EPUBファイルを作成する
                using (ZipStorer zip = ZipStorer.Create(dstFileName, string.Empty))
                {
                    zip.EncodeUTF8 = true;

                    //mimetypeファイルを書き込む 先頭・無圧縮
                    WriteFileToZip(zip, mimeTypeFile, "mimetype", ZipStorer.Compression.Store);

                    //ディレクトリの内容を書き込む
                    WriteDirToZip(zip, srcDir, string.Empty);
                }
            }
        }
Пример #16
0
        protected override void Execute(CodeActivityContext context)
        {
            console           = ActivityConsole.GetDefaultOrNew(context);
            hideConsoleOutput = SuppressConsoleOutput.Get(context);

            List <string> includePaths = IncludePaths.Get(context);
            string        outputFile   = OutputFile.Get(context);
            string        comment      = Comment.Get(context) ?? string.Empty;

            try
            {
                using (ZipStorer zipStorer = ZipStorer.Create(outputFile, comment))
                {
                    foreach (string includePath in includePaths)
                    {
                        FileAttributes attr          = File.GetAttributes(includePath);
                        DirectoryInfo  directoryInfo = new DirectoryInfo(includePath);

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            AddDirectory(zipStorer, directoryInfo, string.Empty, 0);
                        }
                        else
                        {
                            AddFile(zipStorer, includePath, directoryInfo.Name, string.Empty, 0);
                        }
                    }
                }
            }
            catch
            {
                try
                {
                    File.Delete(outputFile);
                }
                catch { }
                throw;
            }
        }
Пример #17
0
        public void FromStream(
            Stream sourceStream,
            IStorageService blobStorage,
            QueryBlobsReadFilterDelegate queryBlobsFilter)
        {
            using (var zipStorer = ZipStorer.Open(sourceStream, FileAccess.Read))
            {
                IEnumerable <ZipStorer.ZipFileEntry> zipEntries = zipStorer.ReadCentralDir();

                if (queryBlobsFilter != null)
                {
                    zipEntries = zipEntries.Where(entry => {
                        bool passed = true;
                        queryBlobsFilter(entry.FilenameInZip, entry.FileSize, entry.ModifyTime, ref passed);
                        return(passed);
                    });
                }

                // Copy data from zip stream to BLOBs
                foreach (var entry in zipEntries)
                {
                    string fileName = Path.GetFileName(entry.FilenameInZip);

                    // Skip if we have no filename
                    if (string.IsNullOrEmpty(fileName))
                    {
                        continue;
                    }

                    // Read zip entry and store it as BLOB
                    using (var writeStream = new MemoryStream())
                    {
                        zipStorer.ExtractFile(entry, writeStream);

                        blobStorage.WriteStorage(entry.FilenameInZip, writeStream.ToArray());
                    }
                }
            }
        }
Пример #18
0
        protected override void FlushCore()
        {
            // Ensure that all the data has been read out of the package
            // stream already. Otherwise we'll lose data when we recreate the zip

            foreach (ZipPackagePart part in Parts.Values)
            {
                part.GetStream();
            }
            if (!PackageStream.CanSeek)
            {
                return;
            }
            // Empty the package stream
            PackageStream.Position = 0;
            PackageStream.SetLength(0);

            // Recreate the zip file
            using (ZipStorer archive = ZipStorer.Create(PackageStream, "", false))
            {
                // Write all the part streams
                foreach (ZipPackagePart part in Parts.Values)
                {
                    Stream partStream = part.GetStream();
                    partStream.Seek(0, SeekOrigin.Begin);

                    archive.AddStream(ZipStorer.Compression.Deflate, part.Uri.ToString().Substring(1), partStream,
                                      DateTime.UtcNow, "");
                }

                using (var ms = new MemoryStream())
                {
                    WriteContentType(ms);
                    ms.Seek(0, SeekOrigin.Begin);

                    archive.AddStream(ZipStorer.Compression.Deflate, ContentUri, ms, DateTime.UtcNow, "");
                }
            }
        }
Пример #19
0
        bool SelfUpdate()
        {
            label1.Text = "Updating updater =)";
            string oldUpdater = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.FriendlyName);

            ZipStorer.ZipFileEntry updater;
            try
            {
                updater = (from entry in updatePackageCatalog where entry.FilenameInZip == AppDomain.CurrentDomain.FriendlyName select entry).Single();
            }
            catch (InvalidOperationException exc)
            {
                return(false);
            }
            if (ZipStorer.CalculateCrc32(oldUpdater) != updater.Crc32)
            {
                File.Move(oldUpdater, String.Format("{0}.tmp", oldUpdater));
                return(updatePackage.ExtractFile(updater, oldUpdater));;
            }

            return(false);
        }
Пример #20
0
        public static void ExtractNativeBinary(Stream resourceStream, string destPath)
        {
            var zipStream = resourceStream;

            // using ZipStorer (nuget pkg) here instead of ZipArchive (.NET built in) because older versions of mono don't support it
            using (var zip = ZipStorer.Open(zipStream, FileAccess.Read))
            {
                string nativeCodeFilename = $"native_code_{GetCurrentPlatform().ToFriendlyString().ToLower()}_{GetArchString()}";
                foreach (var entry in zip.ReadCentralDir())
                {
                    if (entry.FilenameInZip == nativeCodeFilename)
                    {
                        using (var f = File.OpenWrite(destPath))
                            zip.ExtractFile(entry, f);

                        return;
                    }
                }

                throw new PlatformNotSupportedException("This package does not contain native code for your platform");
            }
        }
Пример #21
0
        public static PersonContainer ParseFromFile()
        {
            var zipFilePath = Path.Combine(Environment.CurrentDirectory, "Resources", ZipFileName);

            using (var zipStorer = ZipStorer.Open(zipFilePath, FileAccess.Read))
            {
                var zipDir = zipStorer.ReadCentralDir();
                foreach (var zipEntry in zipDir)
                {
                    if (Path.GetFileName(zipEntry.FilenameInZip) == JsonFileName)
                    {
                        using (var ms = new MemoryStream())
                        {
                            zipStorer.ExtractFile(zipEntry, ms);
                            var json = Encoding.UTF8.GetString(ms.ToArray());
                            return(JsonConvert.DeserializeObject <PersonContainer>(json));
                        }
                    }
                }
                return(null);
            }
        }
Пример #22
0
 /// <summary>
 /// zip压缩
 /// </summary>
 /// <param name="paths">文件绝对路径</param>
 /// <param name="zipPath">zip文件绝对路径</param>
 /// <returns>是否压缩成功</returns>
 public static bool CreateZip(List <string> paths, string zipPath)
 {
     using (ZipStorer zip = ZipStorer.Create(zipPath, string.Empty))
     {
         List <Tuple <string, string> > exPathWithRels = new List <Tuple <string, string> >(); //绝对路径 zip中的相对路径
         foreach (string path in paths)
         {                                                                                     //参数中所有路径
             if (File.Exists(path))
             {                                                                                 //文件
                 zip.AddFile(ZipStorer.Compression.Deflate, path, Path.GetFileName(path), string.Empty);
             }
             else if (Directory.Exists(path))
             {                                                                  //文件夹
                 int           pathLength = Path.GetDirectoryName(path).Length; //获取目录长度
                 List <string> exPaths    = TPath.GetFilePaths(path);           //获取文件夹中所有文件 包含子目录中文件
                 foreach (string exPath in exPaths)
                 {
                     exPathWithRels.Add(Tuple.Create(exPath, exPath.Remove(0, pathLength)));
                 }
             }
             else
             {
                 throw new InvalidOperationException("路径非法:" + path);
             }
         }
         foreach (var path in exPathWithRels)
         {
             if (File.Exists(path.Item1))
             { //文件夹中文件路径
                 zip.AddFile(ZipStorer.Compression.Deflate, path.Item1, path.Item2, string.Empty);
             }
             else
             {
                 throw new InvalidOperationException("路径非法:" + path);
             }
         }
     }
     return(true);
 }
Пример #23
0
        static ArchiveExtractor()
        {
            RegisterExtractor(stream =>
            {
                var archive = ZipStorer.Open(stream, FileAccess.Read);

                var root = Folder.Root;

                foreach (var entry in archive.ReadCentralDir())
                {
                    if (!entry.FilenameInZip.EndsWith("/"))
                    {
                        var ms = new MemoryStream();
                        archive.ExtractFile(entry, ms);
                        ms.Position = 0;
                        root.PathAddFile(entry.FilenameInZip, FileData.FromStream(ms));
                    }
                }

                return(root);
            });
        }
Пример #24
0
        internal static OpfPackage CreatePackage(XElement element, ZipStorer gz, string opsFolder, out string ncx)
        {
            var package = new OpfPackage
            {
                Version    = element.Attribute("version").Value,
                Identifier = element.Attribute("unique-identifier").Value,
                MetaData   = MetaData.CreateMetaData(element.Element(OpfNameSpace + "metadata")),
                Spine      = Spine.CreateSpine(element.Element(OpfNameSpace + "spine"))
            };
            var manifestElement = element.Element(OpfNameSpace + "manifest");
            var ncxElement      = package.Spine.Toc;

            // we need to pull it directly from XML as this file does not become part of the items
            ncx = manifestElement
                  .Elements(OpfNameSpace + "item")
                  .First(item => item.Attribute("id").Value == ncxElement)
                  .Attribute("href")
                  .Value;
            package.Manifest = Manifest.CreateManifest(gz, manifestElement, ncxElement, opsFolder);
            package.Guide    = Guide.CreateGuide(element);
            return(package);
        }
Пример #25
0
        //Epubにファイルを追加する(mimetypeを除く)
        private static void WriteEpubFilesToZip(ZipStorer zip, string srcDir)
        {
            var files       = Directory.GetFiles(srcDir, "*", SearchOption.AllDirectories);     //全ファイル
            var targetFiles = files.Where(e => Path.GetFileName(e).Equals("mimetype") != true)  //mimetypeを除く
                              .Select(e => new FileInfo(e));

            foreach (var targetFile in targetFiles)
            {
                var ext         = targetFile.Extension;
                var compression = new ZipStorer.Compression();
                switch (ext)
                {
                case "jpg":     //画像ファイルは圧縮しない(時間の無駄なので)
                case "JPEG":
                case "png":
                case "PNG":
                case "gif":
                case "GIF":
                    compression = ZipStorer.Compression.Store;
                    break;

                case "EPUB":
                case "epub":
                    continue;       //EPUBファイルは格納しない

                default:
                    compression = ZipStorer.Compression.Deflate;      //通常のファイルは圧縮する
                    break;
                }
                //対象を書き込む
                using (var ms = new MemoryStream(File.ReadAllBytes(targetFile.FullName)))
                {
                    ms.Position = 0;                                             //ファイルの先頭からコピー
                    var fileNameInZip = GetRelPath(targetFile.FullName, srcDir); //zip内でのファイル名
                    zip.AddStream(compression, fileNameInZip, ms, DateTime.Now, string.Empty);
                }
            }
        }
Пример #26
0
        private bool DownloadAndExtractNewTempFiles()
        {
            var data = _webClient.DownloadData(_downloadUrl);

            using (var archive = ZipStorer.Open(new MemoryStream(data), FileAccess.Read))
            {
                var entries    = archive.ReadCentralDir();
                var extractOps = _fileOps.FindAll(o => o.Operation == FileOperationType.ExtractFile);
                foreach (var op in extractOps)
                {
                    var entryIdx = entries.FindIndex(e => e.FilenameInZip == op.FilePath);
                    if (entryIdx < 0)
                    {
                        if (op.AllowedToFail)
                        {
                            continue;
                        }
                        else
                        {
                            return(false);
                        }
                    }

                    var entry   = entries[entryIdx];
                    var success = archive.ExtractFile(entry, op.FilePath + UpdaterHelper.NewFileExtension);
                    if (success)
                    {
                        AddUndoDelete(op.FilePath + UpdaterHelper.NewFileExtension);
                    }
                    else if (!success && !op.AllowedToFail)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Пример #27
0
            public static void Run(Uri url, Guid GUID, ZipStorer Stage)
            {
                var engine = Engines.IronPython.CreateEngine();

                using (MemoryStream engineStream = new MemoryStream())
                {
                    engine.Runtime.IO.SetOutput(engineStream, Encoding.UTF8);
                    engine.Runtime.IO.SetErrorOutput(engineStream, Encoding.UTF8);

                    var scope = engine.CreateScope();

                    scope.SetVariable("URL", url);
                    scope.SetVariable("GUID", GUID);
                    scope.SetVariable("IronPythonDLL", Assembly.Load(Internals.GetResourceInZip(Stage, "IronPython.dll")));
#if DEBUG
                    scope.SetVariable("DEBUG", true);
#elif RELEASE
                    scope.SetVariable("DEBUG", false);
#endif
                    byte[] mainPyFile = Internals.GetResourceInZip(Stage, "Main.py");
                    engine.Execute(Encoding.UTF8.GetString(mainPyFile, 0, mainPyFile.Length), scope);
                }
            }
Пример #28
0
        public string ToBase64String()
        {
            string result = string.Empty;

            this.WriteToDisk();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (ZipStorer zipStorer = ZipStorer.Create(memoryStream, string.Empty))
                {
                    string[] files = Directory.GetFiles(this.profileDir, "*.*", SearchOption.AllDirectories);
                    string[] array = files;
                    for (int i = 0; i < array.Length; i++)
                    {
                        string text          = array[i];
                        string fileNameInZip = text.Substring(this.profileDir.Length).Replace(Path.DirectorySeparatorChar, '/');
                        zipStorer.AddFile(ZipStorer.CompressionMethod.Deflate, text, fileNameInZip, string.Empty);
                    }
                }
                result = Convert.ToBase64String(memoryStream.ToArray());
                this.Clean();
            }
            return(result);
        }
Пример #29
0
        private void ButtonBrowse4_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            dlg.AddExtension    = true;
            dlg.CheckFileExists = true;
            dlg.Multiselect     = false;
            dlg.Title           = "Select storage file";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                TextStorage4.Text = dlg.FileName;

                // Opens existing zip file
                ZipStorer zip = ZipStorer.Open(TextStorage4.Text, FileAccess.Read);

                // Read all directory contents
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                listBox4.Tag = zip;  // keep the zipstorer alive

                listBox4.DataSource = dir;
            }
        }
Пример #30
0
        static string ReadMassiveRemoteZipFileButJavaCodeOnly(string url)
        {
            HighTimeoutWebclient wc = new HighTimeoutWebclient();

            wc.Encoding = UTF8;
            byte[] received = null;
            try
            {
                received = wc.DownloadData(url);
            }
            catch (Exception ex)
            {
                Logger.Output(LogType.ERROR, "Failed to read MassiveRemoteZip: " + ex.ToString() + " for " + url);
                return("");
            }
            wc.Dispose();
            MemoryStream ms = new MemoryStream(received);

            Logger.Output(LogType.DEBUG, "Received " + received.Length + " bytes to parse from <" + url + ">...");
            ZipStorer     zs    = ZipStorer.Open(ms, FileAccess.Read);
            StringBuilder toret = new StringBuilder();

            foreach (ZipStorer.ZipFileEntry zfe in zs.ReadCentralDir())
            {
                if (zfe.FilenameInZip.Contains(".java"))
                {
                    MemoryStream mes = new MemoryStream();
                    zs.ExtractFile(zfe, mes);
                    byte[] bytes = mes.ToArray();
                    mes.Close();
                    toret.Append("/<FILE:" + zfe.FilenameInZip + "\n");
                    toret.Append(UTF8.GetString(bytes));
                }
            }
            ms.Close();
            return(toret.ToString());
        }
Пример #31
0
        /// <summary>
        /// Removes one of many files in storage. It creates a new Zip file.
        /// </summary>
        /// <param name="_zip">
        /// Reference to the current Zip object
        /// </param>
        /// <param name="_zfes">
        /// List of Entries to remove from storage
        /// </param>
        /// <returns>
        /// True if success, false if not
        /// </returns>
        /// <remarks>
        /// This method only works for storage of type FileStream
        /// </remarks>
        public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes)
        {
            if (!(_zip.ZipFileStream is FileStream))
            {
                throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream");
            }

            // Get full list of entries
            List<ZipFileEntry> fullList = _zip.ReadCentralDir();

            // In order to delete we need to create a copy of the zip file excluding the selected items
            string tempZipName = Path.GetTempFileName();
            string tempEntryName = Path.GetTempFileName();

            try
            {
                ZipStorer tempZip = Create(tempZipName, string.Empty);

                foreach (ZipFileEntry zfe in fullList)
                {
                    if (!_zfes.Contains(zfe))
                    {
                        if (_zip.ExtractFile(zfe, tempEntryName))
                        {
                            tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment);
                        }
                    }
                }

                _zip.Close();
                tempZip.Close();

                File.Delete(_zip.FileName);
                File.Move(tempZipName, _zip.FileName);

                _zip = Open(_zip.FileName, _zip.Access);
            }
            catch
            {
                return false;
            }
            finally
            {
                if (File.Exists(tempZipName))
                {
                    File.Delete(tempZipName);
                }

                if (File.Exists(tempEntryName))
                {
                    File.Delete(tempEntryName);
                }
            }

            return true;
        }
Пример #32
0
        /// <summary>
        /// Method to open an existing storage from stream
        /// </summary>
        /// <param name="_stream">Already opened stream with zip contents</param>
        /// <param name="_access">File access mode for stream operations</param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Open(Stream _stream, FileAccess _access, bool _ownsStream = false)
        {
            if (!_stream.CanSeek && _access != FileAccess.Read)
                throw new InvalidOperationException("Stream cannot seek");

            ZipStorer zip = new ZipStorer();
            //zip.FileName = _filename;
            zip.ZipFileStream = _stream;
            zip.OwnsStream = _ownsStream;
            zip.Access = _access;

            if (zip.ReadFileInfo())
                return zip;

            throw new System.IO.InvalidDataException();
        }
Пример #33
0
        /// <summary>
        /// Method to create a new zip storage in a stream
        /// </summary>
        /// <param name="_stream">
        /// </param>
        /// <param name="_comment">
        /// </param>
        /// <returns>
        /// A valid ZipStorer object
        /// </returns>
        public static ZipStorer Create(Stream _stream, string _comment)
        {
            var zip = new ZipStorer();
            zip.Comment = _comment;
            zip.ZipFileStream = _stream;
            zip.Access = FileAccess.Write;

            return zip;
        }
Пример #34
0
        /// <summary>
        /// Method to open an existing storage from stream
        /// </summary>
        /// <param name="_stream">
        /// Already opened stream with zip contents
        /// </param>
        /// <param name="_access">
        /// File access mode for stream operations
        /// </param>
        /// <returns>
        /// A valid ZipStorer object
        /// </returns>
        public static ZipStorer Open(Stream _stream, FileAccess _access)
        {
            if (!_stream.CanSeek && _access != FileAccess.Read)
            {
                throw new InvalidOperationException("Stream cannot seek");
            }

            var zip = new ZipStorer();

            // zip.FileName = _filename;
            zip.ZipFileStream = _stream;
            zip.Access = _access;

            if (zip.ReadFileInfo())
            {
                return zip;
            }

            throw new InvalidDataException();
        }
Пример #35
0
        /// <summary>
        ///     Method to open an existing storage from stream
        /// </summary>
        /// <param name="_stream">Already opened stream with zip contents</param>
        /// <param name="_access">File access mode for stream operations</param>
        /// <returns>A valid ZipStorer object</returns>
        private static ZipStorer Open(Stream _stream, FileAccess _access)
        {
            if (!_stream.CanSeek && _access != FileAccess.Read)
                throw new InvalidOperationException("Stream cannot seek");

            var zip = new ZipStorer {ZipFileStream = _stream, Access = _access};
            //zip.FileName = _filename;

            if (zip.ReadFileInfo())
                return zip;

            throw new InvalidDataException();
        }
Пример #36
0
        /// <summary>
        ///     Method to create a new zip storage in a stream
        /// </summary>
        /// <param name="_stream"></param>
        /// <param name="_comment"></param>
        /// <returns>A valid ZipStorer object</returns>
        private static ZipStorer Create(Stream _stream, string _comment)
        {
            var zip = new ZipStorer {Comment = _comment, ZipFileStream = _stream, Access = FileAccess.Write};

            return zip;
        }
        internal ZipStorer zip = null; // The zip storer holding the main XLSX file stream

        #endregion Fields

        #region Constructors

        // Constructor from a file name
        public OoXml(string template_filename)
        {
            zip = ZipStorer.Open(template_filename, FileAccess.Read);                                                           // Open the template
            foreach (ZipStorer.ZipFileEntry l in zip.ReadCentralDir()) streams.Add(new gStream(this, zip, l));                  // Get the streams that make up the template and add them
            SetStructure();                                                                                                     // Analyzes the Sheets structure
        }
Пример #38
0
 /// <summary>
 ///     Method to create a new zip storage in a stream
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="comment"></param>
 /// <returns>A valid ZipStorer object</returns>
 public static ZipStorer Create(Stream stream, string comment)
 {
     var zip = new ZipStorer {_comment = comment, _zipFileStream = stream, _access = FileAccess.Write};
     return zip;
 }
Пример #39
0
        /// <summary>
        /// Method to create a new zip storage in a stream
        /// </summary>
        /// <param name="_stream"></param>
        /// <param name="_comment"></param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Create(Stream _stream, string _comment, bool _ownsStream = false)
        {
            ZipStorer zip = new ZipStorer();
            zip.Comment = _comment;
            zip.ZipFileStream = _stream;
            zip.OwnsStream = _ownsStream;
            zip.Access = FileAccess.Write;

            return zip;
        }
Пример #40
0
        /// <summary>
        ///     Method to open an existing storage from stream
        /// </summary>
        /// <param name="stream">Already opened stream with zip contents</param>
        /// <param name="access">File access mode for stream operations</param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Open(Stream stream, FileAccess access)
        {
            if (!stream.CanSeek && access != FileAccess.Read)
                throw new InvalidOperationException("Stream cannot seek");

            var zip = new ZipStorer {_zipFileStream = stream, _access = access};

            if (zip.ReadFileInfo())
                return zip;

            throw new InvalidDataException();
        }
        internal ZipStorer.ZipFileEntry zfe; // This is the ZipFileEntry where the stream is stored

        #endregion Fields

        #region Constructors

        // This constructor is called when creating the stream from the source template
        public gStream(OoXml doc, ZipStorer zip, ZipStorer.ZipFileEntry z)
        {
            Document = doc;                                                                                                     // Save a reference to the document
            zfe = z;                                                                                                            // Store the ZipFileEntry
        }
Пример #42
0
 public static void AddText( this ZipStorer self, ZipStorer.Compression _method, string _text, string _filenameInZip, DateTime _modTime, string _comment )
 {
     byte[] bytes = Encoding.UTF8.GetBytes( _text );
     MemoryStream stream = new MemoryStream( bytes );
     self.AddStream( _method, _filenameInZip, stream, _modTime, _comment );
 }
 // Close the excel file
 public void Close()
 {
     if (zip != null) { zip.Close(); zip = null; }
 }