Example #1
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);
        }
    }
Example #2
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;
            });
        }
    }
Example #3
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");
        }
Example #4
0
 /// <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);
        }
Example #6
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();
        }
        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);
            }
        }
Example #8
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");
    }
Example #9
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) { }
        }
        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();
            }
        }
Example #11
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);
     }
 }
Example #12
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);
            }
        }
        /// <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()));
                        }
                    }
                }
        }
Example #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);
     }
 }
        public void Install(string profileDirectory)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(profileDirectory);
            string        text          = Path.Combine(Path.GetTempPath(), directoryInfo.Name + ".staging");
            string        text2         = Path.Combine(text, Path.GetFileName(this.extensionFileName));

            if (Directory.Exists(text2))
            {
                Directory.Delete(text2, true);
            }
            Directory.CreateDirectory(text2);
            Stream resourceStream = ResourceUtilities.GetResourceStream(this.extensionFileName, this.extensionResourceId);

            using (ZipStorer zipStorer = ZipStorer.Open(resourceStream, 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(text2, path);
                    zipStorer.ExtractFile(current, destinationFileName);
                }
            }
            string path2 = FirefoxExtension.ReadIdFromInstallRdf(text2);
            string text3 = Path.Combine(Path.Combine(profileDirectory, "extensions"), path2);

            if (Directory.Exists(text3))
            {
                Directory.Delete(text3, true);
            }
            Directory.CreateDirectory(text3);
            FileUtilities.CopyDirectory(text2, text3);
            FileUtilities.DeleteDirectory(text);
        }
Example #16
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);
        }
Example #17
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();
            }
        }
        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();
            }
        }
Example #19
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);
        }
        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");
            }
        }
Example #21
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();
        }
    }
        /// <summary>
        /// Extract a zip file.
        /// </summary>
        /// <param name="desinationFolder">The destination folder for zip file extraction</param>
        /// <param name="collisionOption">How to deal with collisions with existing files.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A task with a List of strings containing the names of extracted files from the zip archive.</returns>
        public async Task <List <string> > ExtractZipAsync(IFolder desinationFolder, NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting, CancellationToken cancellationToken = default(CancellationToken))
        {
            //Extraction fails on Android if the zip files comes from the asset folder; couldnt' find out why
            var extractedFilenames = new List <string>();
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    ZipStorer zip = ZipStorer.Open(_path, System.IO.FileAccess.Read);
                    //// Read all directory contents
                    List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
                    //// Extract all files in target directory
                    foreach (ZipStorer.ZipFileEntry entry in dir)
                    {
                        bool result = false;
                        var path    = System.IO.Path.Combine(desinationFolder.Path, System.IO.Path.GetFileName(entry.FilenameInZip));
                        if (System.IO.File.Exists(path))
                        {
                            if (collisionOption == NameCollisionOption.ReplaceExisting)
                            {
                                System.IO.File.Delete(path);
                                result = zip.ExtractFile(entry, path);
                            }
                        }
                        else
                        {
                            result = zip.ExtractFile(entry, path);
                        }
                        if (result)
                        {
                            extractedFilenames.Add(entry.FilenameInZip);
                        }
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }
                    }
                    zip.Close();
                }
                catch (Exception)
                {
                }
            }, cancellationToken);

            return(extractedFilenames);
        }
Example #23
0
        /// <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);
        }
Example #24
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);
     }
 }
Example #25
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
        var fullList = _zip.ReadCentralDir();

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

        try
        {
            var tempZip = ZipStorer.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 = ZipStorer.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);
    }
Example #26
0
        } // LoadPack(Stream stream)

        private static Stream Unpack(Stream packedStream)
        {
            Stream    memStream = new MemoryStream();
            ZipStorer zip       = ZipStorer.Open(packedStream, FileAccess.Read);
            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

            zip.ExtractFile(dir[0], memStream);
            memStream.Seek(0, SeekOrigin.Begin);

            return(memStream);
        }
Example #27
0
        public static MemoryStream WriteZipFileToMemory(string internalFileName, string text, string comment)
        {
            MemoryStream csvBytes = new MemoryStream(Encoding.UTF8.GetBytes(text));
            ZipStorer    zip      = ZipStorer.Create(csvBytes, "");

            zip.AddStream(ZipStorer.Compression.Deflate, internalFileName, csvBytes, DateTime.Now, comment);
            var ms = new MemoryStream();
            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

            zip.ExtractFile(dir[0], ms);
            return(ms);
        }
Example #28
0
        private void Unzip(String installerZipAddress)
        {
            ZipStorer installerZip = ZipStorer.Open(installerZipAddress, FileAccess.Read);
            List <ZipStorer.ZipFileEntry> zipDir = installerZip.ReadCentralDir();

            foreach (ZipStorer.ZipFileEntry file in zipDir)
            {
                installerZip.ExtractFile(file,
                                         Path.Combine(_targetInstallFolder, file.FilenameInZip));
            }
            installerZip.Close();
        }
Example #29
0
 public static byte[] GetResourceInZip(ZipStorer zip, string resourceName)
 {
     foreach (var entry in zip.ReadCentralDir())
     {
         if (entry.FilenameInZip == resourceName)
         {
             var resdata = new byte[entry.FileSize];
             zip.ExtractFile(entry, out resdata);
             return(resdata);
         }
     }
     return(default);
        private void ExtractFilesAndCopy()
        {
            logTextBox.AppendText("Extracting Files\n");
            ZipStorer zip = ZipStorer.Open(@"" + pathText.Text + "\\Bazar\\Liveries\\Temp.zip", FileAccess.Read);
            List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();
            // Look for the desired file
            int fileNumber = 0;

            progressBar1.Value = 0;
            foreach (ZipStorer.ZipFileEntry entry in dir)
            {
                //Deleting the first folder for extraction
                string fileName = entry.FilenameInZip.Substring(10, entry.FilenameInZip.Length - 10);
                logTextBox.AppendText("Extracting: " + fileName + "\n");
                zip.ExtractFile(entry, pathText.Text + "\\Bazar\\Liveries\\" + fileName);
                progressBar1.Value = ((fileNumber++ / dir.Count()) * 100);
            }
            zip.Close();
            logTextBox.AppendText("All Files Extracted\n");
            logTextBox.AppendText("Deleting Temporal Files...\n");
            File.Delete("" + pathText.Text + "\\Bazar\\Liveries\\Temp.zip");

            foreach (OptionalDownload optionalPackage in optionaldownloads)
            {
                //Extrat A-10C Files
                string path = "C:\\Users\\" + Environment.UserName + "\\Saved Games\\DCS\\Kneeboard\\" + optionalPackage.folderName;
                if (!Directory.Exists(path))
                {
                    // Try to create the directory.
                    DirectoryInfo di = Directory.CreateDirectory(path);
                }
                ZipStorer zipA10 = ZipStorer.Open("C:\\Users\\" + Environment.UserName + "\\Saved Games\\DCS\\Kneeboard\\" + optionalPackage.folderName + "\\Temp.zip", FileAccess.Read);
                List <ZipStorer.ZipFileEntry> dirA10 = zipA10.ReadCentralDir();
                // Look for the desired file
                int fileNumberA10 = 0;
                progressBar1.Value = 0;
                foreach (ZipStorer.ZipFileEntry entry in dirA10)
                {
                    //Deleting the first folder for extraction
                    string fileName = entry.FilenameInZip;
                    logTextBox.AppendText("Extracting: " + fileName + "\n");
                    zipA10.ExtractFile(entry, "C:\\Users\\" + Environment.UserName + "\\Saved Games\\DCS\\Kneeboard\\" + optionalPackage.folderName + "\\" + fileName);
                    progressBar1.Value = ((fileNumberA10++ / dirA10.Count()) * 100);
                }
                zipA10.Close();
                logTextBox.AppendText(optionalPackage.packageName + " Optional Files Extracted\n");
                logTextBox.AppendText("Deleting " + optionalPackage.packageName + " Optional Temporal Files...\n");
                File.Delete("C:\\Users\\" + Environment.UserName + "\\Saved Games\\DCS\\Kneeboard\\" + optionalPackage.folderName + "\\Temp.zip");
            }
            logTextBox.AppendText("Update/Install Proccess COMPLETED\n");
            pathText.ReadOnly = false;
            System.Media.SystemSounds.Hand.Play();
        }
Example #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;
        }