예제 #1
0
        public static string FileToString(string fileName)
        {
            ZipStorer zip = ZipStorer.Open(fileName, System.IO.FileAccess.Read);

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

            if (dir.Count == 0)
            {
                throw new Exception("no files in " + fileName);
            }

            byte[] block = new byte[0];
            using (var ms = new MemoryStream())
            {
                zip.ExtractFile(dir[0], ms);
                block = ms.ToArray();
            }

            string recs = System.Text.Encoding.Default.GetString(block, 0, block.Length);

            zip.Close();

            return(recs);
        }
예제 #2
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(5000);
            try
            {
                WebClient wc = new WebClient();
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                wc.DownloadFile("https://sergi4ua.com/equine/EQUINEUpdate.zip", Application.StartupPath + "\\..\\equineupdate.zip");

                ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\..\\equineupdate.zip", FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    zip.ExtractFile(entry, Application.StartupPath + "\\..\\" + entry.FilenameInZip);
                }
                zip.Close();
                File.Delete(Application.StartupPath + "\\..\\equineupdate.zip");
                System.Threading.Thread.Sleep(2000);
                MessageBox.Show("EQUINE has been successfully updated!\nEQUINE will now restart.", "EQUINE", MessageBoxButtons.OK, MessageBoxIcon.Information);
                var SelfProc = new ProcessStartInfo
                {
                    UseShellExecute  = true,
                    WorkingDirectory = Application.StartupPath + "\\..\\",
                    FileName         = Application.StartupPath + "\\..\\EQUINE.exe",
                };
                Process.Start(SelfProc);
                Application.Exit();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Update failed!\nWindows reported the error: " + ex.Message + "\nEQUINE will now quit. Please contact EQUINE developers to report this issue.", "Critical error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Application.Exit();
            }
        }
예제 #3
0
        /// <summary>
        /// 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>
        /// <param name="_leaveOpen">true to leave the stream open after the ZipStorer object is disposed; otherwise, false (default).</param>
        /// <returns>A valid ZipStorer object</returns>
        public static ZipStorer Open(Stream _stream, FileAccess _access, bool _leaveOpen = false)
        {
            if (!_stream.CanSeek && _access != FileAccess.Read)
            {
                throw new InvalidOperationException("Stream cannot seek");
            }

            ZipStorer zip = new ZipStorer
            {
                ZipFileStream = _stream,
                Access        = _access,
                leaveOpen     = _leaveOpen
            };

            if (zip.ReadFileInfo())
            {
                foreach (var file in zip.ReadCentralDir())
                {
                    zip.Files[file.FilenameInZip] = file;
                }
                return(zip);
            }

            if (!_leaveOpen)
            {
                zip.Close();
            }

            throw new InvalidDataException();
        }
예제 #4
0
        private Stream GetFileStreamFromXap(string file)
        {
            MemoryStream rv = null;

            ZipStorer zip = ZipStorer.Open(FilePath, FileAccess.Read);

            List <ZipStorer.ZipFileEntry> entries = zip.ReadCentralDir();

            // Look for the desired file
            foreach (ZipStorer.ZipFileEntry entry in entries)
            {
                if (Path.GetFileName(entry.FilenameInZip) == file)
                {
                    rv = new MemoryStream(2048);

                    zip.ExtractFile(entry, rv);

                    rv.Seek(0, SeekOrigin.Begin);

                    break;
                }
            }

            zip.Close();

            return(rv);
        }
예제 #5
0
    public void Begin(int p, string url)
    {
        mVersion = p;
        int v = PlayerPrefs.GetInt("UnPackVersion", 0);

        if (mVersion > v)
        {
            TextAsset ta = (TextAsset)Resources.Load("Game");

            using (MemoryStream ms = new MemoryStream(ta.bytes))
            {
                ZipStorer zip = ZipStorer.Open(ms, FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    string outPath = Application.persistentDataPath + "/" + entry.FilenameInZip;
                    zip.ExtractFile(entry, outPath);
                }
                zip.Close();
            }
            PlayerPrefs.SetInt("UnPackVersion", mVersion);
            GameObject dGo = new GameObject("Downloader");
            mDownloader = dGo.AddComponent <PatcherDownloader>();
            mDownloader.BeginDownload(url, delegate(PatcherElem e)
            {
                mCurElems = e;
                GameObject.Destroy(dGo);
                mDownloader = null;
            });
        }
    }
예제 #6
0
        private bool Install(string s)
        {
            try
            {
                if (!Directory.Exists(s))
                {
                    Directory.CreateDirectory(s);
                }
                using (ZipStorer zip = ZipStorer.Open(Path.GetTempPath() + @"\exercism.zip", FileAccess.Read))
                {
                    List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                    foreach (ZipStorer.ZipFileEntry entry in dir)
                    {
                        zip.ExtractFile(entry, s + @"\exercism.exe");
                    }
                }

                string pathContent = Environment.GetEnvironmentVariable("PATH") + ";" + _installationPath;
                Environment.SetEnvironmentVariable("PATH", pathContent, EnvironmentVariableTarget.User);

                File.Delete(Path.GetTempPath() + @"\exercism.zip");
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                WebClient wc = new WebClient();
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                wc.DownloadFile("https://sergi4ua.com/equine/EquineData.zip", Application.StartupPath + "\\equinedata.zip");

                ZipStorer zip = ZipStorer.Open(Application.StartupPath + "\\equinedata.zip", FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    zip.ExtractFile(entry, Application.StartupPath + "\\EquineData\\" + entry.FilenameInZip);
                }
                zip.Close();
                File.Delete("equinedata.zip");
                System.Threading.Thread.Sleep(2000);
                MessageBox.Show("EquineData updated successfully!\nEQUINE should now restart.", "EQUINE", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Initalization failed!\n" + ex.Message + "\nEQUINE will now quit.", "Critical error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Application.Exit();
            }
        }
예제 #8
0
    public void BeginUnPack(int p, System.Action onFinish, bool debug)
    {
        mVersion  = p;
        mOnFinish = onFinish;
        int v = UnPackBundle;

        if (mVersion > v && !debug)
        {
            TextAsset ta = (TextAsset)Resources.Load("Game");

            using (MemoryStream ms = new MemoryStream(ta.bytes))
            {
                ZipStorer zip = ZipStorer.Open(ms, FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    string outPath = Application.persistentDataPath + "/" + entry.FilenameInZip;
                    zip.ExtractFile(entry, outPath);
                }
                zip.Close();
            }
            UnPackBundle = mVersion;
        }
        if (null != onFinish)
        {
            onFinish();
        }
    }
        public void downloadBinary()
        {
            Directory.CreateDirectory(this.basePath);

            using (var client = new WebClient())
            {
                Console.WriteLine("Downloading BrowserStackLocal Zip..");
                client.DownloadFile(downloadURL, this.zipAbsolute);
                Console.WriteLine("Opening Zip..");
                ZipStorer zip = ZipStorer.Open(this.zipAbsolute, FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    if (Path.GetFileName(entry.FilenameInZip) == binaryName)
                    {
                        zip.ExtractFile(entry, this.binaryAbsolute);
                        break;
                    }
                }
                zip.Close();

                File.Delete(this.zipAbsolute);

                Console.WriteLine("Binary Extracted");
            }
        }
예제 #10
0
        private void WC_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (File.Exists("latest_cats.zip.progress"))
            {
                if (File.Exists("latest_cats.zip"))
                {
                    File.Delete("latest_cats.zip");
                }

                File.Move("latest_cats.zip.progress", "latest_cats.zip");

                ZipStorer zip = ZipStorer.Open("latest_cats.zip", FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                // Look for the desired file
                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    zip.ExtractFile(entry, entry.FilenameInZip);
                }

                zip.Close();
                File.Delete("latest_cats.zip");
            }

            System.Diagnostics.Process.Start("CATSBot.exe");
            Application.Exit();
        }
예제 #11
0
    public void Decompress(string fileName)
    {
        try
        {
            string directoryPath = Server.MapPath("../QuizTests/").ToString();

            if (File.Exists(directoryPath + fileName))
            {
                ZipStorer zst = ZipStorer.Open(directoryPath + fileName, FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zst.ReadCentralDir();
                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    if (Path.GetFileName(entry.FilenameInZip) == "index.html")
                    {
                        zst.ExtractFile(entry, directoryPath + "HtmlQuiz1\\" + "index.html");
                    }
                    else
                    {
                        zst.ExtractFile(entry, directoryPath + "HtmlQuiz1\\" + entry.FilenameInZip);
                    }
                }
                zst.Close();
            }
        }
        catch (Exception ex)
        {
            Response.Redirect(ex.Message);
        }
    }
예제 #12
0
파일: TZip.cs 프로젝트: wnmwi/ToolBox
 /// <summary>
 /// zip解压
 /// </summary>
 /// <param name="zipPath">zip文件路径</param>
 /// <param name="outPath">解压路径</param>
 /// <returns>是否解压成功</returns>
 public static bool UnZip(string zipPath, string outPath)
 {
     //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
     if (!outPath.EndsWith("\\") && !outPath.EndsWith("/"))
     {
         outPath += "\\";
     }
     if (!Directory.Exists(outPath))
     {
         Directory.CreateDirectory(outPath);
     }
     using (ZipStorer zip = ZipStorer.Open(zipPath, FileAccess.Read))
     {
         List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); //获取zip文件内所有文件路径
         foreach (ZipStorer.ZipFileEntry entry in dir)
         {
             if (!zip.ExtractFile(entry, outPath + entry.FilenameInZip))
             {
                 return(false);                                                        //存在没有解压成功的
             }
         }
         zip.Close();
     }
     return(true);
 }
        /// <summary>
        /// Loads the .nuspec file inside the .nupkg file at the given filepath.
        /// </summary>
        /// <param name="nupkgFilepath">The filepath to the .nupkg file to load.</param>
        /// <returns>The .nuspec file loaded from inside the .nupkg file.</returns>
        public static NuspecFile FromNupkgFile(string nupkgFilepath)
        {
            NuspecFile nuspec = new NuspecFile();

            if (File.Exists(nupkgFilepath))
            {
                // get the .nuspec file from inside the .nupkg
                using (ZipStorer zip = ZipStorer.Open(nupkgFilepath, FileAccess.Read))
                {
                    var entry = zip.ReadCentralDir().First(x => x.FilenameInZip.EndsWith(".nuspec"));

                    using (MemoryStream stream = new MemoryStream())
                    {
                        zip.ExtractFile(entry, stream);
                        stream.Position = 0;

                        nuspec = Load(stream);
                    }
                }
            }
            else
            {
                UnityEngine.Debug.LogErrorFormat("Package could not be read: {0}", nupkgFilepath);

                //nuspec.Id = packageId;
                //nuspec.Version = packageVersion;
                nuspec.Description = string.Format("COULD NOT LOAD {0}", nupkgFilepath);
            }

            return(nuspec);
        }
예제 #14
0
 public Stream getIcon()
 {
     if (apk != null)
     {
         Stream memoryStream = new MemoryStream();
         using (ZipStorer zipStorer = ZipStorer.Open(pathApk, FileAccess.Read))
         {
             foreach (ZipStorer.ZipFileEntry zipFileEntry in zipStorer.ReadCentralDir())
             {
                 if (!zipFileEntry.FilenameInZip.Equals(apk.AppIcon))
                 {
                     continue;
                 }
                 zipStorer.ExtractFile(zipFileEntry, memoryStream);
                 break;
             }
             zipStorer.Close();
         }
         return(memoryStream);
     }
     else
     {
         return(null);
     }
 }
예제 #15
0
        private void ButtonProceed4_Click(object sender, EventArgs e)
        {
            List <ZipStorer.ZipFileEntry> removeList = new List <ZipStorer.ZipFileEntry>();

            foreach (object sel in listBox4.SelectedItems)
            {
                removeList.Add((ZipStorer.ZipFileEntry)sel);
            }

            ZipStorer zip = listBox4.Tag as ZipStorer;

            try
            {
                if (zip == null || !ZipStorer.RemoveEntries(ref zip, removeList))
                {
                    throw new Exception();
                }
                else
                {
                    MessageBox.Show("Zip file entries removed with success", "ZipStorer Demo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    listBox4.Tag        = zip;
                    listBox4.DataSource = zip.ReadCentralDir();
                }
            }
            catch
            {
                MessageBox.Show("Error while trying to remove entries from Zip file", "ZipStorer Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #16
0
        private void ExtractEtl(string tempVspxPath, string tempEtlPath)
        {
            OnStatusUpdated(ProfilerState.Stopping, "Extracting ETL file from profiler output...");

            ZipStorer vspx = ZipStorer.Open(tempVspxPath, FileAccess.Read);

            List <ZipStorer.ZipFileEntry> entries = vspx.ReadCentralDir();

            // Look for the etl
            foreach (ZipStorer.ZipFileEntry entry in entries)
            {
                if (entry.FilenameInZip.EndsWith(".etl"))
                {
                    vspx.ExtractFile(entry, tempEtlPath);

                    vspx.Close();

                    return;
                }
            }

            vspx.Close();

            throw new FileNotFoundException("Couldn't find an etl file in the vspx that we retrieved from the device");
        }
예제 #17
0
    public static void UpdateAndroidPlugin()
    {
        var pluginFolder = CombinePaths(Application.dataPath, "Plugins",
                                        "NativeFileSO", "Android");
        var aarPath = CombinePaths(pluginFolder, "NativeFileSO.aar");

        var manifestName = "AndroidManifest.xml";
        var manifestPath = CombinePaths(pluginFolder, manifestName);

        ZipStorer zip = ZipStorer.Open(aarPath, FileAccess.ReadWrite);

        var centralDir = zip.ReadCentralDir();
        var manifest   = centralDir.Find(x => Path.GetFileName(x.FilenameInZip)
                                         == manifestName);

        zip.ExtractFile(manifest, manifestPath);
        UpdateManifestAssociations(manifestPath);

        ZipStorer.RemoveEntries(ref zip, new List <ZipStorer.ZipFileEntry>()
        {
            manifest
        });
        zip.AddFile(ZipStorer.Compression.Deflate, manifestPath, manifest.FilenameInZip, "");

        zip.Close();

        File.Delete(manifestPath);

        Debug.Log("NativeFileSO: Finished updating the Android plugin");
    }
예제 #18
0
        public void Data()
        {
            var counter = 0;
            var file    = new LogFileWriter("test3.zip", "LogFileWriterTestsData");
            var source  = new MemoryPool("test", MemoryAddress.StaticAbsolute, 0x123456, 0, 0x1234);

            source.Add(new MemoryFieldFunc <int>("testInt", (pool) => counter++)); // these are always logged
            source.Add(new MemoryFieldFunc <string>("test", (pool) => "test"));

            file.Subscribe(source);

            // Fill up  a data file
            for (int i = 0; i < 1441792; i++) // 38.5MiB
            {
                file.Update(i);               // +28 bytes
            }
            // We should have logged 2 data files by now.
            Assert.True(File.Exists("LogFileWriterTestsData/test/Data.bin"));

            file.Save();

            ZipStorer z = ZipStorer.Open("test3.zip", FileAccess.Read);

            var files = z.ReadCentralDir();

            Assert.AreEqual(3, files.Count);
            Assert.True(files.Any(x => x.FilenameInZip == "test/Data.bin"));
            Assert.True(files.Where(x => x.FilenameInZip == "test/Data.bin").FirstOrDefault().FileSize ==
                        1441792 * ((2 + 4 + 4 + 2) + (2 + 4 + 4 + 4 + 2)));
            Assert.True(files.Any(x => x.FilenameInZip == "test/Structure.xml"));
            Assert.True(files.Any(x => x.FilenameInZip == "test/Time.bin"));
            Assert.True(files.Where(x => x.FilenameInZip == "test/Time.bin").FirstOrDefault().FileSize == 1441792 * 8);
        }
예제 #19
0
        //To delete or move to old files
        void MoveFolderToOld(string oldPath, string newPath)
        {
            if (File.Exists(oldPath + ".old"))
            {
                File.Delete(oldPath + ".old");
            }

            if (File.Exists(oldPath))
            {
                File.Move(oldPath, oldPath + ".old");
            }

            File.Move(newPath, oldPath);
            Console.WriteLine("移动文件:" + newPath + "到" + oldPath);
            Config config = Config.LoadConfig(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConstFile.FILENAME));

            if (config.Type.ToUpper() == "ZIP")
            {
                Console.WriteLine("读取压缩文件:" + oldPath);
                ZipStorer zip = ZipStorer.Open(oldPath, FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    Console.WriteLine("解压文件:" + entry.FilenameInZip);
                    zip.ExtractFile(entry, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, entry.FilenameInZip));
                }
                zip.Close();
            }
        }
예제 #20
0
 private void ImportGdb(string FileName)
 {
     if (Path.GetExtension(FileName).Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
     {
         using (ZipStorer zip = ZipStorer.Open(FileName, FileAccess.Read))
         {
             List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
             foreach (ZipStorer.ZipFileEntry entry in dir)
             {
                 string gdbFileName = Path.GetFileName(entry.FilenameInZip);
                 if (Path.GetExtension(gdbFileName).Equals(".gdb") || Path.GetExtension(gdbFileName).Equals(".s3db"))
                 {
                     string ganjoorPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ganjoor");
                     if (!Directory.Exists(ganjoorPath))
                     {
                         Directory.CreateDirectory(ganjoorPath);
                     }
                     string gdbExtractPath = Path.Combine(ganjoorPath, gdbFileName);
                     if (zip.ExtractFile(entry, gdbExtractPath))
                     {
                         ganjoorView.ImportDb(gdbExtractPath);
                         File.Delete(gdbExtractPath);
                     }
                 }
             }
         }
     }
     else
     {
         ganjoorView.ImportDb(FileName);
     }
 }
예제 #21
0
        public void Update()
        {
            if (!Check())
            {
                return;
            }

            try
            {
                string zipFileName = Path.Combine(Application.StartupPath, "update.zip");
                // Opens existing zip file
                ZipStorer zip = ZipStorer.Open(zipFileName, FileAccess.Read);

                // Read all directory contents
                List <ZipStorer.ZipFileEntry> zipFiles = zip.ReadCentralDir();

                // Extract all files in target directory
                foreach (ZipStorer.ZipFileEntry entry in zipFiles)
                {
                    if (zip.ExtractFile(entry, Path.Combine(Application.StartupPath, Path.GetFileName(entry.FilenameInZip))))
                    {
                        MainLogger.Append("Extracted: " + entry.FilenameInZip, LogMessageType.Info);
                    }
                    else
                    {
                        MainLogger.Append("Extract failed: " + entry.FilenameInZip, LogMessageType.Info);
                    }
                }

                zip.Close();

                File.Delete(zipFileName);
            }
            catch (Exception) { }
        }
        /// <summary>
        /// Extracts a file's contents from the embedded zip archive into memory.
        /// </summary>
        private static void ExtractTemplateZipToMemory()
        {
            string appJavaPath = BuildTargetAndroid.Instance.GetCompiledPath(BuildTargetAndroid.STUDIO_PROJECT_DIR, "app", "src", "main", "java",
                                                                             AndroidMetadata.PackageName.Replace('.', System.IO.Path.DirectorySeparatorChar));

            using (MemoryStream zipStream = new MemoryStream(Properties.Resources.templateZip))
                using (ZipStorer zip = ZipStorer.Open(zipStream, FileAccess.Read))
                {
                    List <ZipStorer.ZipFileEntry> files = zip.ReadCentralDir(); // get list of files in the zip
                    foreach (ZipStorer.ZipFileEntry entry in files)
                    {
                        string filenameInZip = entry.FilenameInZip;
                        string fullPath      = BuildTargetAndroid.Instance.GetCompiledPath(BuildTargetAndroid.STUDIO_PROJECT_DIR, filenameInZip);
                        bool   isAppJavaFile = filenameInZip.StartsWith("app") && filenameInZip.EndsWith(".java");
                        if (isAppJavaFile)
                        {
                            fullPath = System.IO.Path.Combine(appJavaPath, System.IO.Path.GetFileName(filenameInZip));
                        }
                        TemplateFilePath shortName = new TemplateFilePath(filenameInZip, fullPath);
                        using (MemoryStream stream = new MemoryStream((int)entry.FileSize))
                        {
                            zip.ExtractFile(entry, stream);
                            _files.Add(shortName, new TemplateFile(shortName, stream.ToArray()));
                        }
                    }
                }
        }
예제 #23
0
        private static void ExtractMediaFiles(string zipFullPath, string tempPath)
        {
            try
            {
                ZipStorer zip = ZipStorer.Open(zipFullPath, FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

                Regex regex = new Regex(SlideXmlSearchPattern);

                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    string name = Path.GetFileName(entry.FilenameInZip);

                    if (name?.Contains(".wav") ?? false ||
                        regex.IsMatch(name))
                    {
                        zip.ExtractFile(entry, tempPath + name);
                    }
                }

                zip.Close();

                FileDir.DeleteFile(zipFullPath);
            }
            catch (Exception e)
            {
                ErrorDialogBox.ShowDialog(CommonText.ErrorExtract, "Archived files cannot be retrieved.", e);
            }
        }
예제 #24
0
 public void ReadAccessTime_Test()
 {
     using (ZipStorer zip = ZipStorer.Open(sampleFile, FileAccess.Read))
     {
         var dir = zip.ReadCentralDir();
         Assert.IsTrue(dir[0].AccessTime > DateTime.Today);
     }
 }
예제 #25
0
 public void ReadCentralDir_Test()
 {
     using (ZipStorer zip = ZipStorer.Open(sampleFile, FileAccess.Read))
     {
         var dir = zip.ReadCentralDir();
         Assert.AreEqual(dir.Count, 10);
     }
 }
예제 #26
0
 public void ReadModifyTime_Test()
 {
     using (ZipStorer zip = ZipStorer.Open(sampleFile, FileAccess.Read))
     {
         var dir = zip.ReadCentralDir();
         Assert.IsTrue(dir[0].ModifyTime > baseDate);
     }
 }
예제 #27
0
파일: XMindAPI.cs 프로젝트: wnmwi/ToolBox
        /// <summary>
        /// Loads an XMind workbook file from disk.
        /// </summary>
        private void Load()
        {
            if (_fileName == null)
            {
                throw new InvalidOperationException("No XMind file to load!");
            }

            if (File.Exists(_fileName) == false)
            {
                throw new InvalidOperationException("XMind file does not exist!");
            }

            FileInfo xMindFileInfo = new FileInfo(_fileName);

            if (xMindFileInfo.Extension.ToLower() != ".xmind")
            {
                throw new InvalidOperationException("XMind file extension expected!");
            }

            String tempPath = Path.GetTempPath() + Guid.NewGuid() + "\\";

            Directory.CreateDirectory(tempPath);

            string[] fileNameStrings = xMindFileInfo.Name.Split('.');
            fileNameStrings[fileNameStrings.Count() - 1] = "zip";

            StringBuilder zipFileNameBuilder = new StringBuilder(string.Empty, 64);

            foreach (string str in fileNameStrings)
            {
                zipFileNameBuilder.Append(str + ".");
            }
            string zipFileName = zipFileNameBuilder.ToString().TrimEnd('.');

            // Make a temporary copy of the XMind file with a .zip extention for J# zip libraries:
            File.Copy(_fileName, tempPath + zipFileName);
            File.SetAttributes(tempPath + zipFileName, FileAttributes.Normal);  // Make sure the .zip temporary file is not read only - we want to delete it later...

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

                foreach (ZipStorer.ZipFileEntry entry in dir)
                {
                    zip.ExtractFile(entry, tempPath +
                                    (entry.FilenameInZip == "manifest.xml" ? "META-INF\\" : "") +
                                    entry.FilenameInZip);
                }
                zip.Close();
            }

            _metaData     = XDocument.Parse(File.ReadAllText(tempPath + "meta.xml"));
            _manifestData = XDocument.Parse(File.ReadAllText(tempPath + "META-INF\\manifest.xml"));
            _contentData  = XDocument.Parse(File.ReadAllText(tempPath + "content.xml"));

            Directory.Delete(tempPath, true);
        }
예제 #28
0
 public List <string> words = new List <string>();                                                                       // The XLSX dictionary
 public OoXml(string template_filename)                                                                                  // Constructor from a file name
 {
     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
 }
 public void ReadObjectItem(Stream stream, Func <object, int, bool> putItem)
 {
     stream.Position = 0;
     using (ZipStorer zipStorer = ZipStorer.Open(stream, FileAccess.Read))
     {
         int noOfItems = zipStorer.ReadCentralDir().Count;
         for (int i = 0; i < noOfItems; i++)
         {
             //zipStorer.ExtractFile(new ZipStorer.ZipFileEntry() { FilenameInZip = index.ToString() }, unzipStraem);
             using (var unzipStraem = new MemoryStream())
             {
                 zipStorer.ExtractFile(zipStorer.ReadCentralDir()[i], unzipStraem);
                 unzipStraem.Position = 0;
                 putItem(base.ReadObject(unzipStraem), i);
             }
         }
     }
 }
예제 #30
0
 public void ExtractFile_Test()
 {
     using (ZipStorer zip = ZipStorer.Open(sampleFile, FileAccess.Read))
     {
         var dir = zip.ReadCentralDir();
         Assert.IsFalse(dir.Count == 0);
         zip.ExtractFile(dir[4], out byte[] output);
         Assert.IsFalse(output.Length == 0);
     }
 }
        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
        }
예제 #32
0
파일: ZipStorer.cs 프로젝트: soygul/NBug
        /// <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;
        }