System.IO.Compression.ZipArchiveEntry.Open()

Here are the examples of the csharp api System.IO.Compression.ZipArchiveEntry.Open() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

153 Examples 7

19 Source : songdatabase.cs
with GNU Lesser General Public License v3.0
from angturil

public static string readzipjson(ZipArchive archive,string filename="info.json")
                {
                var info = archive.Entries.First<ZipArchiveEntry>(e => (e.Name.EndsWith(filename)));
                if (info == null) return "";

                StreamReader reader = new StreamReader(info.Open());
                string result=reader.ReadToEnd();
                reader.Close();
                return result;
            }

19 Source : BackupFileService.cs
with MIT License
from AntonyCorbett

public void WriteNewDatabase(
            BackupFile backup, 
            string newDatabaseFilePath, 
            string originalJwlibraryFilePathForSchema)
        {
            if (backup == null)
            {
                throw new ArgumentNullException(nameof(backup));
            }

            ProgressMessage(" Checking validity");
            backup.Database.CheckValidity();

            ProgressMessage("Writing merged database file");

            using var memoryStream = new MemoryStream();
            using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
            {
                Log.Logger.Debug("Created ZipArchive");

                var tmpDatabaseFileName = ExtractDatabaseToFile(originalJwlibraryFilePathForSchema);
                try
                {
                    backup.Manifest.UserDataBackup.DatabaseName = DatabaseEntryName;
                    backup.Manifest.UserDataBackup.Hash = GenerateDatabaseHash(tmpDatabaseFileName);

                    var manifestEntry = archive.CreateEntry(ManifestEntryName);
                    using (var entryStream = manifestEntry.Open())
                    using (var streamWriter = new StreamWriter(entryStream))
                    {
                        streamWriter.Write(
                            JsonConvert.SerializeObject(
                                backup.Manifest,
                                new JsonSerializerSettings
                                {
                                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                                }));
                    }
                    
                    AddDatabaseEntryToArchive(archive, backup.Database, tmpDatabaseFileName);
                }
                finally
                {
                    Log.Logger.Debug("Deleting {tmpDatabaseFileName}", tmpDatabaseFileName);
                    File.Delete(tmpDatabaseFileName);
                }
            }

            using var fileStream = new FileStream(newDatabaseFilePath, FileMode.Create);

            ProgressMessage("Finishing");
                    
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }

19 Source : SlideFile.cs
with MIT License
from AntonyCorbett

private SlidesConfig Load()
        {
            using (var zip = ZipFile.OpenRead(FilePath))
            {
                var configEntry = zip.GetEntry(ConfigEntryName);
                if (configEntry == null)
                {
                    throw new Exception($"Could not find {ConfigEntryName} entry");
                }

                using (var stream = configEntry.Open())
                {
                    var serializer = new JsonSerializer();

                    using (var sr = new StreamReader(stream))
                    using (var jsonTextReader = new JsonTextReader(sr))
                    {
                        var config = serializer.Deserialize<SlidesConfig>(jsonTextReader);
                        if (config == null)
                        {
                            throw new Exception($"Could not read {ConfigEntryName} entry");
                        }

                        return config;
                    }
                }
            }
        }

19 Source : SlideFile.cs
with MIT License
from AntonyCorbett

private static BitmapImage ReadBackgroundImage(ZipArchive zip, string entryName)
        {
            var entry = zip.GetEntry(entryName);
            if (entry == null)
            {
                throw new Exception($"Could not read {entryName} entry");
            }

            using (var stream = entry.Open())
            using (var memoryStream = new MemoryStream())
            { 
                stream.CopyTo(memoryStream);

                BitmapImage bmp;
                try
                {
                    bmp = CreateBitmapImage(memoryStream, ignoreColorProfile: false);
                }
                catch (ArgumentException)
                {
                    // probably colour profile corruption
                    bmp = CreateBitmapImage(memoryStream, ignoreColorProfile: true);
                }

                return bmp;
            }
        }

19 Source : SlideFileBuilder.cs
with MIT License
from AntonyCorbett

private void CreateEmptyArchive(string path, bool overwrite)
        {
            if (File.Exists(path) && !overwrite)
            {
                throw new Exception("File already exists!");
            }

            File.Delete(path);
            if (File.Exists(path))
            {
                throw new Exception("File could not be deleted!");
            }

            _config.Sanitize();

            using (var memoryStream = new MemoryStream())
            {
                using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    var configEntry = zip.CreateEntry(ConfigEntryName);

                    var serializer = new JsonSerializer { Formatting = Formatting.Indented };

                    using (var entryStream = configEntry.Open())
                    using (var entryStreamWriter = new StreamWriter(entryStream))
                    using (var jsonTextWriter = new JsonTextWriter(entryStreamWriter))
                    {
                        serializer.Serialize(jsonTextWriter, _config);
                    }
                }

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    memoryStream.CopyTo(fileStream);
                }
            }
        }

19 Source : SlideFileBuilder.cs
with MIT License
from AntonyCorbett

private static void AddBitmapImageToArchive(ZipArchive zip, string slideArchiveEntryName, BitmapSource slideImage)
        {
            // This is a little odd (multiple streams and rewinding the memory stream!).
            // I can't find a better way of saving a BitmapSource in the archive entry.
            BitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(slideImage));

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

                var entry = zip.CreateEntry(slideArchiveEntryName, CompressionLevel.Optimal);
                using (var entryStream = entry.Open())
                {
                    ms.CopyTo(entryStream);
                }
            }
        }

19 Source : ThemeFile.cs
with MIT License
from AntonyCorbett

public void Create(string themePath, OnlyVTheme theme, string backgroundImagePath, bool overwrite)
        {
            if (string.IsNullOrEmpty(themePath) ||
                !Path.GetExtension(themePath).Equals(ThemeFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException(nameof(themePath));
            }

            if (theme == null)
            {
                throw new ArgumentException(nameof(theme));
            }

            if (File.Exists(themePath) && !overwrite)
            {
                throw new Exception(Properties.Resources.FILE_EXISTS);
            }

            var validBackgroundImage = false;
            if (!string.IsNullOrEmpty(backgroundImagePath))
            {
                var ext = Path.GetExtension(backgroundImagePath);
                if (string.IsNullOrEmpty(ext) ||
                    !ext.Equals(".png", StringComparison.OrdinalIgnoreCase) ||
                    !File.Exists(backgroundImagePath))
                {
                    throw new ArgumentException(nameof(backgroundImagePath));
                }
                
                validBackgroundImage = true;
            }

            using (var memoryStream = new MemoryStream())
            {
                using (var zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    var themeEntry = zip.CreateEntry(ThemeEntryName);

                    var serializer = new JsonSerializer { Formatting = Formatting.Indented };

                    using (var entryStream = themeEntry.Open())
                    using (var entryStreamWriter = new StreamWriter(entryStream))
                    using (var jsonTextWriter = new JsonTextWriter(entryStreamWriter))
                    {
                        serializer.Serialize(jsonTextWriter, theme);
                    }

                    if (validBackgroundImage)
                    {
                        zip.CreateEntryFromFile(backgroundImagePath, ImageEntryName);
                    }
                }

                if (overwrite)
                {
                    File.Delete(themePath);
                }
             
                using (var fileStream = new FileStream(themePath, FileMode.Create))
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    memoryStream.CopyTo(fileStream);
                }
            }
        }

19 Source : ThemeFile.cs
with MIT License
from AntonyCorbett

private static ThemeCacheEntry ReadInternal(string themePath)
        {
            try
            {
                using (var zip = ZipFile.OpenRead(themePath))
                {
                    var entry = zip.GetEntry(ThemeEntryName);
                    if (entry != null)
                    {
                        using (var stream = entry.Open())
                        {
                            var serializer = new JsonSerializer();

                            using (var sr = new StreamReader(stream))
                            using (var jsonTextReader = new JsonTextReader(sr))
                            {
                                var theme = serializer.Deserialize<OnlyVTheme>(jsonTextReader);
                                if (theme != null)
                                {
                                    return new ThemeCacheEntry
                                    {
                                        ThemePath = themePath,
                                        Theme = theme,
                                        BackgroundImage = ReadBackgroundImage(zip)
                                    };
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Could not read theme file");
            }

            return null;
        }

19 Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett

private XDoreplacedent GetXmlFile(string entryPath, bool canCache = false)
        {
            XDoreplacedent result = null;

            if (canCache)
            {
                result = XDocCache.Get(_epubPath, _epubCreationStampUtc, entryPath);
                if (result != null)
                {
                    return result;
                }
            }

            ZipArchiveEntry entry = _zip.Value.GetEntry(entryPath);
            if (entry != null)
            {
                using (var stream = entry.Open())
                using (var sr = new StreamReader(stream))
                {
                    var txt = sr.ReadToEnd();
                    result = XDoreplacedent.Parse(RemoveExtraneousMarkup(txt));
                }
            }

            if (canCache)
            {
                XDocCache.Add(_epubPath, _epubCreationStampUtc, entryPath, result);
            }

            return result;
        }

19 Source : PathfinderUpdaterPlugin.cs
with MIT License
from Arkhist

public override bool Load()
        {
            Config = base.Config;
            
            IsEnabled = Config.Bind<bool>("AutoUpdater", "EnableAutoUpdates", true, "Enables or disables automatic updates for PathfinderAPI");
            EnablePreReleases = Config.Bind<bool>("AutoUpdater", "UsePreReleases", false, "Whether or not to automatically update to beta versions");
            AcceptedUpdate = Config.Bind<string>("AutoUpdater", "LatestAcceptedUpdate", "", "Used internally to keep track of whether you accepted the update or not");
            CurrentVersion = Config.Bind<string>("AutoUpdater", "CurrentVersion", HacknetChainloader.VERSION,
                "Used internally to keep track of version.\nIf you want to skip updating to a version but keep the updater on, set this manually to the latest verison.");

            HarmonyInstance.PatchAll(typeof(PathfinderUpdaterPlugin));
            if (Type.GetType("Mono.Runtime") != null)
            {
                HarmonyInstance.Patch(
                    AccessTools.Method(
                        typeof(ConfigurationManager), "OpenExeConfigurationInternal"),
                    prefix: new HarmonyMethod(AccessTools.Method(typeof(PathfinderUpdaterPlugin), nameof(FixConfig))));
            }

            if (!IsEnabled.Value)
                return true;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var client = new HttpClient();
            client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("a", "1"));
            
            JArray releases;
            try
            {
                releases = JArray.Parse(client
                    .GetAsync("https://api.github.com/repos/Arkhist/Hacknet-Pathfinder/releases").Result.Content
                    .ReadreplacedtringAsync().Result);
            }
            catch (Exception e)
            {
                Log.Log(LogLevel.Error, e);
                client.Dispose();
                return true;
            }

            Version tag = null;
            JToken release = null;
            foreach (var possibleRelease in releases)
            {
                var possibleTag = Version.Parse(possibleRelease.Value<string>("tag_name").Substring(1));
                if (possibleTag.PreRelease != null && !EnablePreReleases.Value)
                    continue;

                tag = possibleTag;
                release = possibleRelease;
                break;
            }

            if (HacknetChainloader.Version.Major != tag.Major)
            {
                Log.LogWarning($"Latest version of Pathfinder is major {tag.Major}, which is higher than Chainloader version {HacknetChainloader.Version.Major}. Please update manually!");
            }

            if (Version.Parse(CurrentVersion.Value).Equals(tag))
                return true;
            
            if (tag.ToString() != AcceptedUpdate.Value)
            {
                VersionToRequest = tag;
                return true;
            }
            
            var archive = new ZipArchive(client.GetAsync(release["replacedets"].First(x => x.Value<string>("name") == "Pathfinder.Release.zip").Value<string>("browser_download_url")).Result.Content.ReadreplacedtreamAsync().Result);
            var pfapiPath = Directory.GetFiles(Paths.PluginPath, "PathfinderAPI.dll", SearchOption.AllDirectories)[0];

            File.Delete(pfapiPath);
            var file = File.OpenWrite(pfapiPath);
            archive.GetEntry("BepInEx/plugins/PathfinderAPI.dll").Open().CopyTo(file);
            file.Flush();
            file.Dispose();
            
            archive.Dispose();
            client.Dispose();

            return true;
        }

19 Source : CdnScriptTagTests.cs
with Apache License 2.0
from aspnet

private static (List<ScriptTag> scripts, List<LinkTag> links) GetTags(string zipFile)
        {
            var scriptTags = new List<ScriptTag>();
            var linkTags = new List<LinkTag>();
            using (var zip = new ZipArchive(File.OpenRead(zipFile), ZipArchiveMode.Read, leaveOpen: false))
            {
                foreach (var entry in zip.Entries)
                {
                    if (!string.Equals(".cshtml", Path.GetExtension(entry.Name), StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    IHtmlDoreplacedent htmlDoreplacedent;
                    var options = new HtmlParserOptions
                    {
                        IsStrictMode = false,
                        IsEmbedded = false,
                    };
                    var config = Configuration.Default;
                    var htmlParser = new HtmlParser(options, config);
                    using (var reader = new StreamReader(entry.Open()))
                    {
                        htmlDoreplacedent = htmlParser.Parse(entry.Open());
                    }

                    foreach (IElement link in htmlDoreplacedent.Body.GetElementsByTagName("link"))
                    {
                        linkTags.Add(new LinkTag
                        {
                            HRef = link.GetAttribute("href"),
                            Integrity = link.GetAttribute("integrity"),
                            FallbackHRef = link.GetAttribute("asp-fallback-href"),
                        });
                    }

                    foreach (var scriptElement in htmlDoreplacedent.Scripts)
                    {
                        var fallbackSrcAttribute = scriptElement.Attributes
                            .FirstOrDefault(attr => string.Equals("asp-fallback-src", attr.Name, StringComparison.OrdinalIgnoreCase));

                        scriptTags.Add(new ScriptTag
                        {
                            Src = scriptElement.Source,
                            Integrity = scriptElement.Integrity,
                            FallbackSrc = fallbackSrcAttribute?.Value,
                            FileName = Path.GetFileName(zipFile),
                            Entry = entry.FullName
                        });
                    }

                }
            }
            return (scriptTags, linkTags);
        }

19 Source : Mods.xaml.cs
with MIT License
from Assistant

private async Task InstallMod(Mod mod, string directory)
        {
            int filesCount = 0;
            string downloadLink = null;

            foreach (Mod.DownloadLink link in mod.downloads)
            {
                filesCount = link.hashMd5.Length;

                if (link.type == "universal")
                {
                    downloadLink = link.url;
                    break;
                }
                else if (link.type.ToLowerInvariant() == App.BeatSaberInstallType.ToLowerInvariant())
                {
                    downloadLink = link.url;
                    break;
                }
            }

            if (string.IsNullOrEmpty(downloadLink))
            {
                System.Windows.MessageBox.Show(string.Format((string)FindResource("Mods:ModDownloadLinkMissing"), mod.name));
                return;
            }

            while (true)
            {
                List<ZipArchiveEntry> files = new List<ZipArchiveEntry>(filesCount);

                using (Stream stream = await DownloadMod(Utils.Constants.BeatModsURL + downloadLink))
                using (ZipArchive archive = new ZipArchive(stream))
                {
                    foreach (ZipArchiveEntry file in archive.Entries)
                    {
                        string fileDirectory = Path.GetDirectoryName(Path.Combine(directory, file.FullName));
                        if (!Directory.Exists(fileDirectory))
                        {
                            Directory.CreateDirectory(fileDirectory);
                        }

                        if (!string.IsNullOrEmpty(file.Name))
                        {
                            foreach (Mod.DownloadLink download in mod.downloads)
                            {
                                foreach (Mod.FileHashes fileHash in download.hashMd5)
                                {
                                    using (Stream fileStream = file.Open())
                                    {
                                        if (fileHash.hash == Utils.CalculateMD5FromStream(fileStream))
                                        {
                                            files.Add(file);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (files.Count == filesCount)
                    {
                        foreach (ZipArchiveEntry file in files)
                        {
                            await ExtractFile(file, Path.Combine(directory, file.FullName), 3.0, mod.name, 10);
                        }

                        break;
                    }
                }
            }

            if (App.CheckInstalledMods)
            {
                mod.Lisreplacedem.IsInstalled = true;
                mod.Lisreplacedem.InstalledVersion = mod.version;
                mod.Lisreplacedem.InstalledModInfo = mod;
            }
        }

19 Source : Themes.cs
with MIT License
from Assistant

private static Theme LoadZipTheme(string directory, string name, string extension)
        {
            Waifus waifus = new Waifus();
            ResourceDictionary dictionary = null;

            using (FileStream stream = new FileStream(Path.Combine(directory, name + extension), FileMode.Open, FileAccess.Read))
            using (ZipArchive archive = new ZipArchive(stream))
            {
                foreach (ZipArchiveEntry file in archive.Entries)
                {
                    bool isPng = file.Name.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
                    bool isSidePng = file.Name.EndsWith(".side.png", StringComparison.OrdinalIgnoreCase);
                    bool isXaml = file.Name.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase);

                    if (isPng && !isSidePng)
                    {
                        waifus.Background = GetImageFromStream(Utils.StreamToArray(file.Open()));
                    }

                    if (isSidePng)
                    {
                        waifus.Sidebar = GetImageFromStream(Utils.StreamToArray(file.Open()));
                    }

                    string videoExtension = $".{file.Name.Split('.').Last()}";
                    if (supportedVideoExtensions.Contains(videoExtension))
                    {
                        string videoName = $"{ThemeDirectory}\\{name}\\_{name}{videoExtension}";
                        Directory.CreateDirectory($"{ThemeDirectory}\\{name}");

                        if (File.Exists(videoName) == false)
                        {
                            file.ExtractToFile(videoName, false);
                        }
                        else
                        {
                            /*
                             * Check to see if the lengths of each file are different. If they are, overwrite what currently exists.
                             * The reason we are also checking LoadedTheme against the name variable is to prevent overwriting a file that's
                             * already being used by Modreplacedistant and causing a System.IO.IOException.
                             */
                            FileInfo existingInfo = new FileInfo(videoName);
                            if (existingInfo.Length != file.Length && LoadedTheme != name)
                            {
                                file.ExtractToFile(videoName, true);
                            }
                        }
                    }

                    if (isXaml && loadedThemes.ContainsKey(name) == false)
                    {
                        try
                        {
                            dictionary = (ResourceDictionary)XamlReader.Load(file.Open());
                        }
                        catch (Exception ex)
                        {
                            string message = string.Format((string)Application.Current.FindResource("Themes:FailedToLoadXaml"), name, ex.Message);
                            MessageBox.Show(message);
                        }
                    }
                }
            }

            Theme theme = new Theme(name, dictionary)
            {
                Waifus = waifus
            };

            return theme;
        }

19 Source : Session.cs
with GNU General Public License v3.0
from BigETI

public static Session Load(string path)
        {
            Session ret = null;
            try
            {
                if (path != null)
                {
                    if (File.Exists(path))
                    {
                        using (ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Read))
                        {
                            ZipArchiveEntry entry = archive.GetEntry("meta.json");
                            if (entry != null)
                            {
                                using (Stream stream = entry.Open())
                                {
                                    SessionDataContract session_data = serializer.ReadObject(stream) as SessionDataContract;
                                    if (session_data != null)
                                    {
                                        ret = new Session(path, session_data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
            return ret;
        }

19 Source : SessionUserControl.cs
with GNU General Public License v3.0
from BigETI

private void ViewSelectedImage()
        {
            Dictionary<string, Process> processes = new Dictionary<string, Process>();
            try
            {
                string temp_path = Path.Combine(Path.GetTempPath(), "SAMPLauncherNET");
                if (!(Directory.Exists(temp_path)))
                {
                    Directory.CreateDirectory(temp_path);
                }
                using (ZipArchive archive = ZipFile.Open(session.Path, ZipArchiveMode.Read))
                {
                    uint id = 0U;
                    foreach (ListViewItem item in galleryListView.SelectedItems)
                    {
                        try
                        {
                            string path = (string)(item.Tag);
                            ZipArchiveEntry entry = archive.GetEntry(path);
                            if (entry != null)
                            {
                                string destination_path;
                                do
                                {
                                    destination_path = Path.Combine(temp_path, "session_" + id + ".png");
                                    ++id;
                                }
                                while (File.Exists(destination_path));
                                using (FileStream file_stream = File.Open(destination_path, FileMode.Create))
                                {
                                    using (Stream stream = entry.Open())
                                    {
                                        stream.CopyTo(file_stream);
                                    }
                                }
                                Process process = Process.Start(destination_path);
                                if (process != null)
                                {
                                    processes.Add(destination_path, process);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Error.WriteLine(e);
                            MessageBox.Show(e.Message, Utils.Translator.GetTranslation("ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e);
            }
            foreach (KeyValuePair<string, Process> process in processes)
            {
                try
                {
                    process.Value.WaitForExit();
                    if (File.Exists(process.Key))
                    {
                        File.Delete(process.Key);
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e);
                }
            }
        }

19 Source : SessionUserControl.cs
with GNU General Public License v3.0
from BigETI

private void gallerySavePictureBox_Click(object sender, EventArgs e)
        {
            saveFileDialog.Filter = "Portable Network Graphics (*.png)|*.png|All files (*.*)|*.*";
            try
            {
                using (ZipArchive archive = ZipFile.Open(session.Path, ZipArchiveMode.Read))
                {
                    foreach (ListViewItem item in galleryListView.SelectedItems)
                    {
                        try
                        {
                            string path = (string)(item.Tag);
                            ZipArchiveEntry entry = archive.GetEntry(path);
                            if (entry != null)
                            {
                                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                                {
                                    try
                                    {
                                        string destination_path = saveFileDialog.FileName;
                                        if (File.Exists(destination_path))
                                        {
                                            File.Delete(destination_path);
                                        }
                                        using (FileStream file_stream = File.Open(destination_path, FileMode.Create))
                                        {
                                            using (Stream stream = entry.Open())
                                            {
                                                stream.CopyTo(file_stream);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.Error.WriteLine(ex);
                                        MessageBox.Show(ex.Message, Utils.Translator.GetTranslation("ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Error.WriteLine(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
        }

19 Source : SAMP.cs
with GNU General Public License v3.0
from BigETI

public static void ChangeSAMPVersion(SAMPVersionDataContract version, bool useInstaller)
        {
            if (version != null)
            {
                DownloadProgressForm dpf = new DownloadProgressForm(useInstaller ? version.InstallationURI : version.ZipURI, Path.GetFullPath("./downloads/" + (useInstaller ? "install.exe" : "client.zip")));
                if (dpf.ShowDialog() == DialogResult.OK)
                {
                    SAMPProvider.ResetVersionCache();
                    try
                    {
                        if (File.Exists(dpf.Path))
                        {
                            if (useInstaller)
                            {
                                Process.Start(dpf.Path);
                                Application.Exit();
                            }
                            else
                            {
                                using (ZipArchive archive = ZipFile.Open(dpf.Path, ZipArchiveMode.Read))
                                {
                                    foreach (ZipArchiveEntry entry in archive.Entries)
                                    {
                                        string path = ExeDir + "\\" + entry.FullName.Replace('/', '\\');
                                        try
                                        {
                                            using (Stream stream = entry.Open())
                                            {
                                                using (FileStream file_stream = new FileStream(path, FileMode.Create))
                                                {
                                                    int b = -1;
                                                    while ((b = stream.ReadByte()) != -1)
                                                    {
                                                        file_stream.WriteByte((byte)b);
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Error.WriteLine(e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                        MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

19 Source : Session.cs
with GNU General Public License v3.0
from BigETI

public static Session Create(string path, DateTime dateTime, TimeSpan timeSpan, string gameVersion, string username, string ipPort, string hostname, string mode, string language, string[] screenshotPaths, string chatlogPath, string savedPositionsPath)
        {
            Session ret = null;
            if (path != null)
            {
                if (path != null)
                {
                    SessionDataContract session_data = new SessionDataContract(dateTime, timeSpan, gameVersion, username, ipPort, hostname, mode, language);
                    try
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        using (ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Create))
                        {
                            ZipArchiveEntry entry = archive.CreateEntry("meta.json");
                            if (entry != null)
                            {
                                using (Stream stream = entry.Open())
                                {
                                    serializer.WriteObject(stream, session_data);
                                }
                            }
                            if (screenshotPaths != null)
                            {
                                foreach (string screenshot_path in screenshotPaths)
                                {
                                    if (screenshot_path != null)
                                    {
                                        if (File.Exists(screenshot_path))
                                        {
                                            archive.CreateEntryFromFile(screenshot_path, "screenshots/" + System.IO.Path.GetFileName(screenshot_path));
                                        }
                                    }
                                }
                            }
                            if (chatlogPath != null)
                            {
                                if (File.Exists(chatlogPath))
                                {
                                    archive.CreateEntryFromFile(chatlogPath, "chatlog.txt");
                                }
                            }
                            if (savedPositionsPath != null)
                            {
                                if (File.Exists(savedPositionsPath))
                                {
                                    archive.CreateEntryFromFile(savedPositionsPath, "saved-positions.txt");
                                }
                            }
                        }
                        ret = new Session(path, session_data);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine(e);
                    }
                }
            }
            return ret;
        }

19 Source : ZipFile.cs
with MIT License
from BizTalkCommunity

public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;
            IBaseMessageContext context = pInMsg.Context;

            // Check if the zip Component is activated
            if (!this.Enabled)
                return pInMsg;

            string fileName = context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties").ToString();

            if (bodyPart != null)
            {
                string bodyPartName = pInMsg.BodyPartName;
                try
                {
                    Stream currentPartSource = pInMsg.BodyPart.GetOriginalDataStream();
                    byte[] currentPartBuffer = new byte[currentPartSource.Length];
                    currentPartSource.Read(currentPartBuffer, 0, currentPartBuffer.Length);
                    byte[] compressedPartBuffer;

                    using (var outStream = new MemoryStream())
                    {
                        outStream.Write(currentPartBuffer, 0, currentPartBuffer.Length);
                        using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
                        {
                            var fileInArchive = archive.CreateEntry(fileName, CompressionLevel.Optimal);

                            using (Stream entryStream = fileInArchive.Open())
                            using (var fileToCompression = new MemoryStream(currentPartBuffer))
                            {
                                fileToCompression.CopyTo(entryStream);
                            }
                        }
                        compressedPartBuffer = outStream.ToArray();
                    }

                    MemoryStream tempMemStream = new MemoryStream(currentPartBuffer);
                    pInMsg.BodyPart.Data = tempMemStream;

                    string sourcePartName = fileName + this.FileExtension;

                    pInMsg.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", sourcePartName);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return pInMsg;

            #endregion
        }

19 Source : UnZipBatch.cs
with MIT License
from BizTalkCommunity

public void Disreplacedemble(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            if (pInMsg.BodyPart != null)
            {
                Stream currentPartSource = pInMsg.BodyPart.GetOriginalDataStream();
                byte[] currentPartBuffer = new byte[currentPartSource.Length];
                currentPartSource.Read(currentPartBuffer, 0, currentPartBuffer.Length);
                byte[] decompressedPartBuffer;

                string filename = "";
                //Unzip arquive
                using (var unzipArchive = new ZipArchive(currentPartSource, ZipArchiveMode.Read, true))
                {
                    //Loop arquive file for message
                    foreach (var entryStream in unzipArchive.Entries)
                    {
                        IBaseMessage inboundInstanceMessage;
                        //Here we are gets the filename (with extension) of an entery present in the arquive file
                        filename = entryStream.FullName; 
                        using (var outStream = new MemoryStream())
                        {
                            entryStream.Open().CopyTo(outStream);
                            decompressedPartBuffer = outStream.ToArray();
                        }
                        
                        MemoryStream messageInstanceStream = new MemoryStream(decompressedPartBuffer);
                        messageInstanceStream.Position = 0;

                        #region Generating a new inbound message 

                        //Creating a new message from the pipeline context
                        inboundInstanceMessage = pContext.GetMessageFactory().CreateMessage();
                        //Cloning the context to the new message, instead of replacedigning it
                        inboundInstanceMessage.Context = PipelineUtil.CloneMessageContext(pInMsg.Context);

                        inboundInstanceMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);
                        inboundInstanceMessage.BodyPart.Data = messageInstanceStream;

                        inboundInstanceMessage.BodyPart.Charset = "UTF-8";
                        inboundInstanceMessage.BodyPart.ContentType = "text/xml";
                        //we promote the filename so that we can access it in the Send Port.
                        inboundInstanceMessage.Context.Promote("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", filename);
                        
                        #endregion

                        inboundMsgQueue.Enqueue(inboundInstanceMessage);
                    }
                }
            }
        }

19 Source : PatcherInstaller.cs
with GNU General Public License v3.0
from Ceiridge

public bool Install(WriteToLog log, List<int> disabledGroups) {
			using (TaskService ts = new TaskService()) {
				foreach (Task task in ts.RootFolder.Tasks) {
					if (task.Name.Equals("ChromeDllInjector")) {
						if (task.State == TaskState.Running) {
							task.Stop();
						}
					}
				}
			}
			SendNotifyMessage(new IntPtr(0xFFFF), 0x0, UIntPtr.Zero, IntPtr.Zero); // HWND_BROADCAST a WM_NULL to make sure every injected dll unloads
			Thread.Sleep(1000); // Give Windows some time to unload all patch dlls

			using (RegistryKey dllPathKeys = OpenExesKey()) {
				foreach (string valueName in dllPathKeys.GetValueNames()) {
					if (valueName.Length > 0) {
						dllPathKeys.DeleteValue(valueName);
					}
				}
				log("Cleared ChromeExes registry");

				int i = 0;
				foreach (InstallationPaths paths in this.installationPaths) {
					string appDir = Path.GetDirectoryName(paths.ChromeExePath!)!;

					// Write patch data info file
					byte[] patchData = GetPatchFileBinary(paths, disabledGroups);
					File.WriteAllBytes(Path.Combine(appDir, "ChromePatches.bin"), patchData);
					log("Wrote patch file to " + appDir);

					// Add chrome dll to the registry key
					dllPathKeys.SetValue(i.ToString(), paths.ChromeExePath!);
					i++;
					log("Appended " + paths.ChromeDllPath + " to the registry key");
				}
			}

			// Write the injector to "Program Files"
			DirectoryInfo programsFolder = GetProgramsFolder();
			string patcherDllPath = Path.Combine(programsFolder.FullName, "ChromePatcherDll_" + Installation.GetUnixTime() + ".dll"); // Unique dll to prevent file locks

			if (!programsFolder.Exists) {
				Directory.CreateDirectory(programsFolder.FullName); // Also creates all subdirectories
			}

			using (ZipArchive zip = new ZipArchive(new MemoryStream(Properties.Resources.ChromeDllInjector), ZipArchiveMode.Read)) {
				foreach (ZipArchiveEntry entry in zip.Entries) {
					string combinedPath = Path.Combine(programsFolder.FullName, entry.FullName);
					new FileInfo(combinedPath).Directory?.Create(); // Create the necessary folders that contain the file

					using Stream entryStream = entry.Open();
					using FileStream writeStream = File.OpenWrite(combinedPath);
					entryStream.CopyTo(writeStream);
				}
			}
			log("Extracted injector zip");

			TryDeletePatcherDlls(programsFolder);
			File.WriteAllBytes(patcherDllPath, Properties.Resources.ChromePatcherDll);
			log("Wrote patcher dll to " + patcherDllPath);

			using (TaskService ts = new TaskService()) {
				TaskDefinition task = ts.NewTask();

				task.RegistrationInfo.Author = "Ceiridge";
				task.RegistrationInfo.Description = "A logon task that automatically injects the ChromePatcher.dll into every Chromium process that the user installed the patcher on. This makes removing the Developer Mode Extension Warning possible.";
				task.RegistrationInfo.URI = "https://github.com/Ceiridge/Chrome-Developer-Mode-Extension-Warning-Patcher";

				task.Triggers.Add(new LogonTrigger { });
				task.Actions.Add(new ExecAction(Path.Combine(programsFolder.FullName, "ChromeDllInjector.exe")));

				task.Principal.RunLevel = TaskRunLevel.Highest;
				task.Principal.LogonType = TaskLogonType.InteractiveToken;

				task.Settings.StopIfGoingOnBatteries = task.Settings.DisallowStartIfOnBatteries = false;
				task.Settings.RestartCount = 3;
				task.Settings.RestartInterval = new TimeSpan(0, 1, 0);
				task.Settings.Hidden = true;
				task.Settings.ExecutionTimeLimit = task.Settings.DeleteExpiredTaskAfter = TimeSpan.Zero;

				Task tsk = ts.RootFolder.RegisterTaskDefinition("ChromeDllInjector", task, TaskCreation.CreateOrUpdate, WindowsIdenreplacedy.GetCurrent().Name, null, TaskLogonType.InteractiveToken);

				if (tsk.State != TaskState.Running) {
					tsk.Run();
				}
				log("Created and started task");
			}

			log("Patches installed!");
			return true;
		}

19 Source : EngineService.cs
with MIT License
from CheshireCaat

private async Task ExtractExecutable(string zipPath)
        {
            OnExtractStarted?.Invoke();
            
            using (var zip = File.OpenRead(zipPath))
            {
                using (var archive = new ZipArchive(zip, ZipArchiveMode.Read))
                {
                    foreach (var entry in archive.Entries)
                    {
                        var path = Path.Combine(ExeDirectory, entry.FullName);

                        if (!entry.FullName.EndsWith("/") || !string.IsNullOrEmpty(entry.Name))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException());

                            using (Stream stream = entry.Open(), file = File.OpenWrite(path))
                            {
                                await stream.CopyToAsync(file).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            Directory.CreateDirectory(path);
                        }
                    }
                }
            }

            OnExtractEnded?.Invoke();
        }

19 Source : Program.cs
with MIT License
from codewitch-honey-crisis

static void Main(string[] _args)
		{
			var exeName = _args[0];
			Console.Error.WriteLine("Downloading from {0}...",_args[1]);
			WebRequest wrq = WebRequest.Create(_args[1]);
			WebResponse wrs = wrq.GetResponse();
			using (var stm = wrs.GetResponseStream())
			{
				// equiv of this. but not available on this platform:
				//zip.ExtractToDirectory(Environment.CurrentDirectory, true);
				var zip = new ZipArchive(stm);
				Console.Error.WriteLine("done!");
				foreach (var entry in zip.Entries)
				{
					Console.Error.Write(string.Concat("Unzipping ", entry.Name, "..."));
					try
					{
						File.Delete(entry.FullName);
					}
					catch { }
					var d = Path.GetDirectoryName(entry.FullName);
					if (!string.IsNullOrEmpty(d))
					{
						try
						{
							Directory.CreateDirectory(d);
						}
						catch { }
					}
					using (var stm1 = entry.Open())
					using (var stm2 = File.OpenWrite(entry.FullName))
						stm1.CopyTo(stm2);
					Console.Error.WriteLine("done!");
				}
			}
			Console.Error.WriteLine("Cleaning up...");
			var psi = new ProcessStartInfo();
			var args = new StringBuilder();
			var delim = "";
			for (var i = 2; i < _args.Length; i++)
			{
				args.Append(delim);
				args.Append(_Esc(_args[i]));
				args.Append(' ');
			}
			psi.FileName = exeName;
			psi.Arguments = args.ToString();
			var proc = Process.Start(psi);
			
		}

19 Source : MainForm.cs
with MIT License
from colinvella

private Stream GetCartridgeRomStream(string cartridgeRomPath)
        {
            Stream cartridgeRomStream = null;

            if (Path.GetExtension(cartridgeRomPath).ToLower() == ".zip")
            {
                Stream zipStream = new FileStream(cartridgeRomPath, FileMode.Open);
                ZipArchive zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read);

                // find first nes file
                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                {
                    if (entry.FullName.EndsWith(".nes", StringComparison.OrdinalIgnoreCase))
                    {
                        cartridgeRomStream = entry.Open();
                        break;
                    }
                }
            }

            if (cartridgeRomStream == null)
                cartridgeRomStream = new FileStream(cartridgeRomPath, FileMode.Open);

            return cartridgeRomStream;
        }

19 Source : Resources.cs
with MIT License
from derplayer

public static ZipFile[] Unzip(byte[] zippedBuffer)
        {
            List<ZipFile> tempList = new List<ZipFile>();

            using (var zippedStream = new MemoryStream(zippedBuffer))
            {
                using (var archive = new ZipArchive(zippedStream))
                {
                    foreach (var entry in archive.Entries)
                    {
                        using (var unzippedEntryStream = entry.Open())
                        {
                            using (var ms = new MemoryStream())
                            {
                                unzippedEntryStream.CopyTo(ms);
                                var unzippedArray = ms.ToArray();
                                tempList.Add(new ZipFile
                                {
                                    Filename = entry.Name,
                                    Content = unzippedArray
                                });
                            }
                        }
                    }

                    return tempList.ToArray();
                }
            }
        }

19 Source : ApkHelper.cs
with Apache License 2.0
from dotMorten

public static void GetAPKInfo(string path, out string apk_id, out string activity)
        {
            apk_id = "";
            activity = "";
            using (MemoryStream ms = new MemoryStream())
            {
                using (var file = System.IO.Compression.ZipFile.OpenRead(path))
                {
                    var entry = file.GetEntry("AndroidManifest.xml");
                    if (entry != null)
                    {
                        using (var manifestStream = entry.Open())
                        {
                            manifestStream.CopyTo(ms);
                            ms.Seek(0, SeekOrigin.Begin);
                        }
                    }
                }
                var reader = new AndroidXmlReader(ms);
                while (reader.Read())
                {
                    if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "manifest")
                    {
                        if (reader.MoveToAttribute("package"))
                        {
                            apk_id = reader.Value;
                        }
                        
                    }
                    else if(reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "activity")
                    {
                        if (reader.MoveToAttribute("name", "http://schemas.android.com/apk/res/android"))
                        {
                            activity = reader.Value;
                        }
                    }
                }
            }
        }

19 Source : Program.cs
with MIT License
from dotnet-ad

public static void Main(string[] args)
        {
            const string DistantZipUri= "https://github.com/feathericons/feather/archive/master.zip";
            const string LocalZipUri = "feathericons.zip";

            if(!File.Exists(LocalZipUri))
            {
                var client = new WebClient();
                client.DownloadFile(DistantZipUri, LocalZipUri);
            }

            var builder = new StringBuilder();

            builder.AppendLine("/// Source: https://feathericons.com/\n");

            builder.AppendLine("using System;");

            builder.AppendLine("namespace SkiaSharp.Components");
            builder.AppendLine("{");
            builder.AppendLine("    public static clreplaced Icons");
            builder.AppendLine("    {");

            string cap = "Round", join = "Round";

            using(var stream = File.OpenRead(LocalZipUri))
            using(var archive = new ZipArchive(stream, ZipArchiveMode.Read))
            {
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    if (entry.FullName.StartsWith("feather-master/icons/", StringComparison.Ordinal) && Path.GetExtension(entry.FullName) == ".svg")
                    {

                        var iconName = string.Join("",Path.GetFileNameWithoutExtension(entry.FullName).Split('-').Select(x => x.Substring(0,1).ToUpper() + x.Substring(1)));

                        builder.AppendLine($"         private static Lazy<Icon> {iconName}Instance = new Lazy<Icon>(() =>");
                        builder.AppendLine("         {");
                        builder.AppendLine("             var source = new SKPath();");

                        using (var content = entry.Open())
                        {
                            var xml = XDoreplacedent.Load(content);

                            foreach (var element in xml.Root.Elements())
                            {
                                var name = element.Name.LocalName;
                                var source = "             source";

                                if (name == "line")
                                {
                                    var x1 = FormatFloat(element.Attribute("x1").Value);
                                    var y1 = FormatFloat(element.Attribute("y1").Value);
                                    var x2 = FormatFloat(element.Attribute("x2").Value);
                                    var y2 = FormatFloat(element.Attribute("y2").Value);
                                    builder.AppendLine($"{source}.MoveTo({x1},{y1});");
                                    builder.AppendLine($"{source}.LineTo({x2},{y2});");
                                }
                                else if(name == "polyline" || name == "polygon")
                                {
                                    var points = element.Attribute("points").Value?.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
                                    for (int i = 0; i < points.Count() ; i++)
                                    {
                                        var x = FormatFloat(points.ElementAtOrDefault(i));
                                        i++;
                                        var y = FormatFloat(points.ElementAtOrDefault(i));

                                        if(i == 1)
                                        {
                                            builder.AppendLine($"{source}.MoveTo({x},{y});");
                                            builder.Append($"{source}.AddPoly(new SKPoint [] {{ ");
                                        }
                                        builder.Append($"new SKPoint({x},{y}),");
                                    }
                                    builder.Append("}");
                                    builder.Append($",{ (name == "polygon" ? "true" : "false") }");
                                    builder.AppendLine(");");
                                }
                                else if (name == "circle")
                                {
                                    var cx = FormatFloat(element.Attribute("cx").Value);
                                    var cy = FormatFloat(element.Attribute("cy").Value);
                                    var r = FormatFloat(element.Attribute("r").Value);
                                    builder.AppendLine($"{source}.AddCircle({cx},{cy},{r});");
                                }
                                else if (name == "rect")
                                {
                                    var x = FormatFloat(element.Attribute("x").Value);
                                    var y = FormatFloat(element.Attribute("y").Value);
                                    var w = FormatFloat(element.Attribute("width").Value);
                                    var h = FormatFloat(element.Attribute("height").Value);
                                    builder.AppendLine($"{source}.AddRect(SKRect.Create({x},{y},{w},{h}));");
                                }
                                else if (name == "path")
                                {
                                    builder.Append($"{source}.AddPath(");
                                    builder.Append($"SKPath.ParseSvgPathData(\"{element.Attribute("d").Value}\")");
                                    builder.AppendLine(", SKPathAddMode.Append);");
                                }


                                if (name == "line")
                                {
                                    var x1 = FormatFloat(element.Attribute("x1").Value);
                                    var y1 = FormatFloat(element.Attribute("y1").Value);
                                    var x2 = FormatFloat(element.Attribute("x2").Value);
                                    var y2 = FormatFloat(element.Attribute("y2").Value);
                                    builder.AppendLine($"{source}.MoveTo({x1},{y1});");
                                    builder.AppendLine($"{source}.LineTo({x2},{y2});");
                                }
                            }

                            switch(xml.Root.Attribute("stroke-linecap")?.Value)
                            {
                                case null:
                                    cap = "Round";
                                    break;

                                case "round":
                                    cap = "Round";
                                    break;

                                case "butt":
                                    cap = "Butt";
                                    break;

                                case "square":
                                    cap = "Square";
                                    break;
                            }

                            switch (xml.Root.Attribute("stroke-linejoin")?.Value)
                            {
                                case null:
                                    join = "Round";
                                    break;

                                case "miter":
                                    join = "Miter";
                                    break;

                                case "bevel":
                                    join = "Bevel";
                                    break;
                            }

                            builder.AppendLine($"             return new Icon(source, SKStrokeCap.{cap}, SKStrokeJoin.{join});");
                            builder.AppendLine("         });");
                            builder.AppendLine($"\n         public static Icon {iconName} => {iconName}Instance.Value;");
                        }
                    }
                } 

                

                builder.AppendLine("    }");
                builder.AppendLine("}");
            }

            File.WriteAllText("../../../SkiaSharp.Components/Base/Icons.cs", builder.ToString());

            Console.WriteLine(builder.ToString());
        }

19 Source : BackupManagerViewModel.cs
with MIT License
from ekblom

private void LoadBackupSet(string fileName)
        {
            var folders = new List<FolderTreeNode>();
            var allTreeNodes = new List<FolderTreeNode>();

            using (var zip = ZipFile.Open(fileName, ZipArchiveMode.Read))
            {
                foreach (var entry in zip.Entries)
                {
                    var path = entry.FullName.Contains("/") ? entry.FullName.Substring(0, entry.FullName.LastIndexOf('/')) : "/";
                    FolderTreeNode parentFolder = null;
                    if (path != "/")
                    {
                        var pathChunks = new Queue<string>(path.Split('/'));
                        while (pathChunks.Any())
                        {
                            var folderName = pathChunks.Dequeue();
                            var node = allTreeNodes.FirstOrDefault(f => f.FolderId == folderName);

                            if (node == null)
                            {
                                node = new FolderTreeNode(folderName, parentFolder);
                                if (parentFolder != null)
                                    parentFolder.Children.Add(node);
                                else
                                    folders.Add(node);

                                parentFolder = node;
                                allTreeNodes.Add(node);
                            }
                            else
                            {
                                parentFolder = node;
                            }
                        }
                    }

                    if (entry.Name.EndsWith(".note"))
                    {
                        var note = ConvertFileInfo<Note>(entry.Open());
                        parentFolder?.Children.Add(new FileTreeNode(entry, note, parentFolder));
                    }
                    else if (entry.Name.EndsWith(".book"))
                    {
                        var nb = ConvertFileInfo<Notebook>(entry.Open());
                        var treeNode = allTreeNodes.FirstOrDefault(n => n.FolderId.ToLowerInvariant() == nb.ID.ToString().ToLowerInvariant());
                        if (treeNode != null)
                        {
                            treeNode.Name = nb.Name;
                            treeNode.Notebook = nb;
                        }
                    }
                }
            }

            SelectedFileNode = null;
            BackupSetNodes.Clear();
            folders.ForEach(BackupSetNodes.Add);
        }

19 Source : ApplicationEndpoint.cs
with GNU General Public License v3.0
from FailedShack

[Request("/zipProxy.php?*")]
        public void GetZipProxy(Session oS)
        {
            var data = GetRequestData(oS);
            byte[] bytes = Convert.FromBase64String(data.Get("url"));
            Uri uri = new Uri(Encoding.UTF8.GetString(bytes));

            string content;
            using (var resp = Program.Proxy.Get(uri).GetResponse())
            {
                var contentType = new ContentType(resp.Headers["Content-Type"]);
                var encoding = Encoding.GetEncoding(contentType.CharSet ?? "UTF-8");
                try
                {
                    using (var reader = new StreamReader(resp.GetResponseStream(), encoding))
                    {
                        content = reader.ReadToEnd();
                    }
                }
                catch (WebException e)
                {
                    Proxy.LogRequest(oS, this, "Unable to download data from " + uri.ToString() + ": " + e);
                    oS.utilCreateResponseAndBypreplacedServer();
                    if (e.Status == WebExceptionStatus.ProtocolError)
                    {
                        var response = (HttpWebResponse)e.Response;
                        oS.oResponse.headers.SetStatus((int)response.StatusCode, response.StatusDescription);
                    }
                    else
                    {
                        oS.oResponse.headers.SetStatus(500, "Internal Server Error: " + e.Status);
                    }
                    return;
                }
            }

            MemoryStream stream = new MemoryStream();
            using (ZipArchive zip = new ZipArchive(stream, ZipArchiveMode.Create))
            {
                var entry = zip.CreateEntry("content");
                using (var streamWriter = new StreamWriter(entry.Open()))
                {
                    streamWriter.Write(content);
                }
            }

            byte[] dataBytes = stream.ToArray();
            oS.utilCreateResponseAndBypreplacedServer();
            oS.oResponse["Content-Length"] = dataBytes.Length.ToString();
            oS.responseBodyBytes = dataBytes;
            Proxy.LogRequest(oS, this, "Created zip from " + uri.ToString());
        }

19 Source : CrashReporter.cs
with GNU General Public License v3.0
from Fe7n

internal string CollectCrashReport(Exception ex)
		{
			Process process = Process.GetCurrentProcess();
			dynamic systemInfo = GenerateSystemProfile(ex);
			string zipTempName = Path.GetTempFileName();
			string dumpTempName = Path.GetTempFileName();
			string reportFileName = string.Format("crash_{0}.zip", DateTime.Now.ToFileTimeUtc());
			string reportPath = Path.Combine(crashReportPath, reportFileName);

			/*
			 * Unfortunately MiniDump is a WIN32 API and crash dumps aren't really generatable by mono at
			 * this time.  There are no readily available heap replacedysis tools and even loading cores via
			 * GDB has no managed support.
			 *
			 * Crash dumps are a windows-only thing atm.
			 */
			if (ServerApi.RunningMono == false)
			{
				if (HeapshotRequesting != null)
				{
					HeapshotRequesting(this, new EventArgs());
				}

				using (FileStream fs = new FileStream(dumpTempName, FileMode.OpenOrCreate))
				{
					if (Native.MiniDumpWriteDump(process.Handle, (uint)process.Id, fs.SafeFileHandle, Native.MINIDUMP_TYPE.WithFullMemory,
						IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == false)
					{
						throw new Win32Exception(Marshal.GetLastWin32Error());
					}
				}
			}

			using (FileStream zipFs = new FileStream(zipTempName, FileMode.OpenOrCreate))
			using (ZipArchive zipArchive = new ZipArchive(zipFs, ZipArchiveMode.Create))
			{
				using (StreamWriter sw = new StreamWriter(zipArchive.CreateEntry("crash.json", CompressionLevel.Optimal).Open()))
				{
					sw.Write(JObject.FromObject(systemInfo).ToString());
				}

				if (ServerApi.RunningMono == false)
				{
					try
					{
						using (FileStream fs = new FileStream(dumpTempName, FileMode.Open))
						{
							fs.CopyTo(zipArchive.CreateEntry("core_" + process.Id + ".dmp", CompressionLevel.Optimal).Open());
						}
					}
					finally
					{
						/*
						 * The memory dmp files are large, and should be axed regardless of if the
						 * process could copy it to the zip file or not.
						 */
						File.Delete(dumpTempName);
					}
				}

			}

			if (Directory.Exists(crashReportPath) == false)
			{
				Directory.CreateDirectory(crashReportPath);
			}

			File.Move(zipTempName, reportPath);

			return reportFileName;
		}

19 Source : LongPathZipFile.cs
with MIT License
from fuse-open

public static void ExtractToDirectory(string zipFile, string targetDir)
        {
            var dirsCreated = new HashSet<string>();
            var archive = ZipFile.Open(zipFile, ZipArchiveMode.Read);
            foreach (var entry in archive.Entries)
            {
                var fullName = entry.FullName.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

                foreach (var dirsToCreate in FindDirectoriesToCreate(dirsCreated, fullName))
                {
                    LongPathDisk.CreateDirectory(Path.Combine(targetDir, dirsToCreate));
                    dirsCreated.Add(dirsToCreate);
                }

                if (fullName.EndsWith(Path.DirectorySeparatorChar.ToString()))
                    continue; // Continue when entry is a directory
                
                using (MemoryStream ms = new MemoryStream())
                {
                    entry.Open().CopyTo(ms);
                    LongPathDisk.WriteAllBytes(Path.Combine(targetDir, fullName), ms.ToArray());
                }
            }
        }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void Example3()
    {
        // Load a Word file.
        var doreplacedent = DoreplacedentModel.Load("Input.docx");

        var imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);

        // Get Word pages.
        var pages = doreplacedent.GetPaginator().Pages;

        // Create a ZIP file for storing PNG files.
        using (var archiveStream = File.OpenWrite("Output.zip"))
        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
        {
            // Iterate through the Word pages.
            for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++)
            {
                DoreplacedentModelPage page = pages[pageIndex];

                // Create a ZIP entry for each doreplacedent page.
                var entry = archive.CreateEntry($"Page {pageIndex + 1}.png");

                // Save each doreplacedent page as a PNG image to the ZIP entry.
                using (var imageStream = new MemoryStream())
                using (var entryStream = entry.Open())
                {
                    page.Save(imageStream, imageOptions);
                    imageStream.CopyTo(entryStream);
                }
            }
        }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void Example2()
    {
        // Load Word file.
        DoreplacedentModel doreplacedent = DoreplacedentModel.Load("Input.docx");

        // Get Word pages.
        var pages = doreplacedent.GetPaginator().Pages;

        // Create PDF save options.
        var pdfSaveOptions = new PdfSaveOptions() { ImageDpi = 220 };

        // Create ZIP file for storing PDF files.
        using (var archiveStream = File.OpenWrite("Output2.zip"))
        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
            // Iterate through Word pages.
            for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++)
            {
                DoreplacedentModelPage page = pages[pageIndex];

                // Create ZIP entry for each doreplacedent page.
                var entry = archive.CreateEntry($"Page {pageIndex + 1}.pdf");

                // Save each doreplacedent page as PDF to ZIP entry.
                using (var pdfStream = new MemoryStream())
                using (var entryStream = entry.Open())
                {
                    page.Save(pdfStream, pdfSaveOptions);
                    pdfStream.CopyTo(entryStream);
                }
            }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        var fileNameWithoutExt = Path.GetFileNameWithoutExtension("LoremIpsum.pdf");

        // Open source PDF file and create a destination ZIP file.
        using (var source = PdfDoreplacedent.Load("LoremIpsum.pdf"))
        using (var archiveStream = File.OpenWrite($"{fileNameWithoutExt}.zip"))
        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, leaveOpen: true))
            for (int index = 0; index < source.Pages.Count; index++)
            {
                // Create new ZIP entry for each source doreplacedent page.
                var entry = archive.CreateEntry($"{fileNameWithoutExt}{index + 1}.pdf");

                // Open ZIP entry stream.
                using (var entryStream = entry.Open())
                // Create destination doreplacedent.
                using (var destination = new PdfDoreplacedent())
                {
                    // Clone source doreplacedent page to destination doreplacedent.
                    destination.Pages.AddClone(source.Pages[index]);

                    // Save destination doreplacedent to ZIP entry stream.
                    destination.Save(entryStream);
                }
            }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void ExtractFilesAndFoldersToArchive(PdfPortfolioFileCollection files, PdfPortfolioFolderCollection folders, ZipArchive archive, string parentFolderFullName, PdfName portfolioFieldKey)
    {
        foreach (var fileSpecification in files)
        {
            // Use the FullName field value or the resolved full name as the relative path of the entry in the zip archive.
            string entryFullName;
            if (fileSpecification.PortfolioFieldValues.TryGet(portfolioFieldKey, out PdfPortfolioFieldValue fullNameValue))
                entryFullName = fullNameValue.ToString();
            else
                entryFullName = parentFolderFullName + fileSpecification.Name;

            var embeddedFile = fileSpecification.EmbeddedFile;

            // Create zip archive entry.
            // Zip archive entry is compressed if the portfolio embedded file's compressed size is less than its uncompressed size.
            bool compress = embeddedFile.Size == null || embeddedFile.CompressedSize < embeddedFile.Size.GetValueOrDefault();
            var entry = archive.CreateEntry(entryFullName, compress ? CompressionLevel.Optimal : CompressionLevel.NoCompression);

            // Set the modification date, if it is specified in the portfolio embedded file.
            var modificationDate = embeddedFile.ModificationDate;
            if (modificationDate != null)
                entry.LastWriteTime = modificationDate.GetValueOrDefault();

            // Copy embedded file contents to the zip archive entry.
            using (var embeddedFileStream = embeddedFile.OpenRead())
            using (var entryStream = entry.Open())
                embeddedFileStream.CopyTo(entryStream);
        }

        foreach (var folder in folders)
        {
            // Use the FullName field value or the resolved full name as the relative path of the entry in the zip archive.
            string folderFullName;
            if (folder.PortfolioFieldValues.TryGet(portfolioFieldKey, out PdfPortfolioFieldValue fullNameValue))
                folderFullName = fullNameValue.ToString();
            else
                folderFullName = parentFolderFullName + folder.Name + '/';

            // Set the modification date, if it is specified in the portfolio folder.
            var modificationDate = folder.ModificationDate;
            if (modificationDate.HasValue)
                archive.CreateEntry(folderFullName).LastWriteTime = modificationDate.GetValueOrDefault();

            // Recursively add to zip archive all files and folders underneath the current portfolio folder.
            ExtractFilesAndFoldersToArchive(folder.Files, folder.Folders, archive, folderFullName, portfolioFieldKey);
        }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void ExtractEmbeddedFiles()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Add to zip archive all files embedded in the PDF doreplacedent.
        using (var doreplacedent = PdfDoreplacedent.Load("Embedded Files.pdf"))
        using (var archiveStream = File.Create("Embedded Files.zip"))
        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, leaveOpen: true))
            foreach (var keyFilePair in doreplacedent.EmbeddedFiles)
            {
                var fileSpecification = keyFilePair.Value;

                // Use the description or the name as the relative path of the entry in the zip archive.
                var entryFullName = fileSpecification.Description;
                if (entryFullName == null || !entryFullName.EndsWith(fileSpecification.Name, StringComparison.Ordinal))
                    entryFullName = fileSpecification.Name;

                var embeddedFile = fileSpecification.EmbeddedFile;

                // Create zip archive entry.
                // Zip archive entry is compressed if the embedded file's compressed size is less than its uncompressed size.
                bool compress = embeddedFile.Size == null || embeddedFile.CompressedSize < embeddedFile.Size.GetValueOrDefault();
                var entry = archive.CreateEntry(entryFullName, compress ? CompressionLevel.Optimal : CompressionLevel.NoCompression);

                // Set the modification date, if it is specified in the embedded file.
                var modificationDate = embeddedFile.ModificationDate;
                if (modificationDate != null)
                    entry.LastWriteTime = modificationDate.GetValueOrDefault();

                // Copy embedded file contents to the zip archive entry.
                using (var embeddedFileStream = embeddedFile.OpenRead())
                using (var entryStream = entry.Open())
                    embeddedFileStream.CopyTo(entryStream);
            }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void CreateEmbeddedFilesFromStreams()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var doreplacedent = PdfDoreplacedent.Load("Reading.pdf"))
        {
            // Make Attachments panel visible.
            doreplacedent.PageMode = PdfPageMode.UseAttachments;

            // Embed in the PDF doreplacedent all the files from the zip archive.
            using (var archiveStream = File.OpenRead("Attachments.zip"))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read, leaveOpen: true))
                foreach (var entry in archive.Entries)
                    if (!string.IsNullOrEmpty(entry.Name))
                    {
                        var fileSpecification = doreplacedent.EmbeddedFiles.AddEmpty(entry.Name).Value;

                        // Set embedded file description to the relative path of the file in the zip archive.
                        fileSpecification.Description = entry.FullName;

                        var embeddedFile = fileSpecification.EmbeddedFile;

                        // Set the embedded file size and modification date.
                        if (entry.Length < int.MaxValue)
                            embeddedFile.Size = (int)entry.Length;
                        embeddedFile.ModificationDate = entry.LastWriteTime;

                        // Copy embedded file contents from the zip archive entry.
                        // Embedded file is compressed if its compressed size in the zip archive is less than its uncompressed size.
                        using (var entryStream = entry.Open())
                        using (var embeddedFileStream = embeddedFile.OpenWrite(compress: entry.CompressedLength < entry.Length))
                            entryStream.CopyTo(embeddedFileStream);
                    }

            doreplacedent.Save("Embedded Files from Streams.pdf");
        }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void CreateFileAttachmentAnnotationsFromStreams()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var doreplacedent = PdfDoreplacedent.Load("Reading.pdf"))
        {
            var page = doreplacedent.Pages[0];
            int rowCount = 0;
            double spacing = page.CropBox.Width / 5,
                left = spacing,
                bottom = page.CropBox.Height - 200;

            // Add file attachment annotations to the PDF page from all the files from the zip archive.
            using (var archiveStream = File.OpenRead("Attachments.zip"))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read, leaveOpen: true))
                foreach (var entry in archive.Entries)
                    if (!string.IsNullOrEmpty(entry.Name))
                    {
                        var fileAttachmentAnnotation = page.Annotations.AddEmptyFileAttachment(left, bottom, entry.Name);

                        // Set a different icon for each file attachment annotation in a row.
                        fileAttachmentAnnotation.Appearance.Icon = (PdfFileAttachmentIcon)(rowCount + 1);

                        // Set attachment description to the relative path of the file in the zip archive.
                        fileAttachmentAnnotation.Description = entry.FullName;

                        var embeddedFile = fileAttachmentAnnotation.File.EmbeddedFile;

                        // Set the embedded file size and modification date.
                        if (entry.Length < int.MaxValue)
                            embeddedFile.Size = (int)entry.Length;
                        embeddedFile.ModificationDate = entry.LastWriteTime;

                        // Copy embedded file contents from the zip archive entry.
                        // Embedded file is compressed if its compressed size in the zip archive is less than its uncompressed size.
                        using (var entryStream = entry.Open())
                        using (var embeddedFileStream = embeddedFile.OpenWrite(compress: entry.CompressedLength < entry.Length))
                            entryStream.CopyTo(embeddedFileStream);

                        // There are, at most, 4 file attachment annotations in a row.
                        ++rowCount;
                        if (rowCount < 4)
                            left += spacing;
                        else
                        {
                            rowCount = 0;
                            left = spacing;
                            bottom -= spacing;
                        }
                    }

            doreplacedent.Save("File Attachment Annotations from Streams.pdf");
        }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void ExtractFilesFromFileAttachmentAnnotations()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        // Add to zip archive all files from file attachment annotations located on the first page.
        using (var doreplacedent = PdfDoreplacedent.Load("File Attachment Annotations.pdf"))
        using (var archiveStream = File.Create("File Attachment Annotation Files.zip"))
        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, leaveOpen: true))
            foreach (var annotation in doreplacedent.Pages[0].Annotations)
                if (annotation.AnnotationType == PdfAnnotationType.FileAttachment)
                {
                    var fileAttachmentAnnotation = (PdfFileAttachmentAnnotation)annotation;

                    var fileSpecification = fileAttachmentAnnotation.File;

                    // Use the description or the file name as the relative path of the entry in the zip archive.
                    var entryFullName = fileAttachmentAnnotation.Description;
                    if (entryFullName == null || !entryFullName.EndsWith(fileSpecification.Name, StringComparison.Ordinal))
                        entryFullName = fileSpecification.Name;

                    var embeddedFile = fileSpecification.EmbeddedFile;

                    // Create zip archive entry.
                    // Zip archive entry is compressed if the embedded file's compressed size is less than its uncompressed size.
                    bool compress = embeddedFile.Size == null || embeddedFile.CompressedSize < embeddedFile.Size.GetValueOrDefault();
                    var entry = archive.CreateEntry(entryFullName, compress ? CompressionLevel.Optimal : CompressionLevel.NoCompression);

                    // Set the modification date, if it is specified in the embedded file.
                    var modificationDate = embeddedFile.ModificationDate;
                    if (modificationDate != null)
                        entry.LastWriteTime = modificationDate.GetValueOrDefault();

                    // Copy embedded file contents to the zip archive entry.
                    using (var embeddedFileStream = embeddedFile.OpenRead())
                    using (var entryStream = entry.Open())
                        embeddedFileStream.CopyTo(entryStream);
                }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void CreatePortfolioFromStreams()
    {
        // If using the Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var doreplacedent = PdfDoreplacedent.Load("PortfolioTemplate.pdf"))
        {
            // Make the doreplacedent a PDF portfolio (a collection of file attachments).
            var portfolio = doreplacedent.SetPortfolio();

            // Add all files and folders from the zip archive to the portfolio.
            using (var archiveStream = File.OpenRead("Attachments.zip"))
            using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read, leaveOpen: true))
                foreach (var entry in archive.Entries)
                {
                    // Get or create portfolio folder hierarchy from the zip entry full name.
                    var folder = GetOrAddFolder(portfolio, entry.FullName);

                    if (!string.IsNullOrEmpty(entry.Name))
                    {
                        // Zip archive entry is a file.
                        var files = folder == null ? portfolio.Files : folder.Files;

                        var embeddedFile = files.AddEmpty(entry.Name).EmbeddedFile;

                        // Set the portfolio file size and modification date.
                        if (entry.Length < int.MaxValue)
                            embeddedFile.Size = (int)entry.Length;
                        embeddedFile.ModificationDate = entry.LastWriteTime;

                        // Copy portfolio file contents from the zip archive entry.
                        // Portfolio file is compressed if its compressed size in the zip archive is less than its uncompressed size.
                        using (var entryStream = entry.Open())
                        using (var embeddedFileStream = embeddedFile.OpenWrite(compress: entry.CompressedLength < entry.Length))
                            entryStream.CopyTo(embeddedFileStream);
                    }
                    else
                        // Zip archive entry is a folder.
                        // Set the portfolio folder modification date.
                        folder.ModificationDate = entry.LastWriteTime;
                }

            // Set the first PDF file contained in the portfolio to be initially presented in the user interface.
            // Note that all files contained in the portfolio are also contained in the PdfDoreplacedent.EmbeddedFiles.
            portfolio.InitialFile = doreplacedent.EmbeddedFiles.Select(entry => entry.Value).FirstOrDefault(fileSpec => fileSpec.Name.EndsWith(".pdf", StringComparison.Ordinal));

            // Hide all existing portfolio fields except 'Size'.
            foreach (var portfolioFieldEntry in portfolio.Fields)
                portfolioFieldEntry.Value.Hidden = portfolioFieldEntry.Value.Name != "Size";

            // Add a new portfolio field with display name 'Full Name' and it should be in the first column.
            var portfolioFieldKeyAndValue = portfolio.Fields.Add(PdfPortfolioFieldDataType.String, "FullName");
            var portfolioField = portfolioFieldKeyAndValue.Value;
            portfolioField.Name = "Full Name";
            portfolioField.Order = 0;

            // For each file and folder in the portfolio, set FullName field value to the relative path of the file/folder in the zip archive.
            SetFullNameFieldValue(portfolio.Files, portfolio.Folders, string.Empty, portfolioFieldKeyAndValue.Key);

            doreplacedent.Save("Portfolio from Streams.pdf");
        }
    }

19 Source : Program.cs
with MIT License
from GemBoxLtd

static void Example3()
    {
        // Load an Excel file.
        var workbook = ExcelFile.Load("CombinedTemplate.xlsx");

        // Get Excel pages.
        var paginatorOptions = new PaginatorOptions() { SelectionType = SelectionType.EntireFile };
        var pages = workbook.GetPaginator(paginatorOptions).Pages;

        // Create a ZIP file for storing PNG files.
        using (var archiveStream = File.OpenWrite("Output.zip"))
        using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create))
        {
            var imageOptions = new ImageSaveOptions();

            // Iterate through the Excel pages.
            for (int pageIndex = 0; pageIndex < pages.Count; pageIndex++)
            {
                ExcelFilePage page = pages[pageIndex];

                // Create a ZIP entry for each spreadsheet page.
                var entry = archive.CreateEntry($"Page {pageIndex + 1}.png");

                // Save each spreadsheet page as a PNG image to the ZIP entry.
                using (var imageStream = new MemoryStream())
                using (var entryStream = entry.Open())
                {
                    page.Save(imageStream, imageOptions);
                    imageStream.CopyTo(entryStream);
                }
            }
        }
    }

19 Source : ModPage.xaml.cs
with MIT License
from Goose-Bomb

private void LoadModInfo(string path)
        {
            ModInfo mod = new ModInfo()
            {
                FileName = Path.GetFileNameWithoutExtension(path),
                IsEnabled = path.EndsWith(".disabled") ? false : true
            };

            using (var archive = ZipFile.OpenRead(path))
            {
                var entry = archive.GetEntry("mcmod.info");
                if (entry != null)
                {
                    string json = new StreamReader(entry.Open(), System.Text.Encoding.UTF8).ReadToEnd();
                    try
                    {
                        JsonData ModInfo = JsonMapper.ToObject(json.Substring(1, json.Length - 1));

                        mod.Name = ModInfo["name"]?.ToString();
                        mod.Description = ModInfo["description"]?.ToString();
                        mod.Url = ModInfo["url"]?.ToString();

                    }
                    catch
                    {

                    };
                }
            }

            if (path.EndsWith(".zip")) FileSystem.RenameFile(path, mod.Name + ".jar");
            if (mod.Name == null) mod.Name = mod.FileName;

            Dispatcher.BeginInvoke((Action)delegate ()
            {
                _currentMods.Add(mod);
            });
        }

19 Source : ResourcepackPage.xaml.cs
with MIT License
from Goose-Bomb

private ResPack GetResPackFromDisk(string path)
        {
            ResPack pack = new ResPack()
            {
                Name = Path.GetFileName(path),
            };

            if (path.EndsWith(".zip"))
            {
                using (var archive = ZipFile.OpenRead(path))
                {
                    using (var sr = new StreamReader(archive.GetEntry("pack.mcmeta").Open(), Encoding.UTF8))
                    {
                        GetPackInfo(sr.ReadToEnd(), ref pack);
                    }

                    using (var stream = archive.GetEntry("pack.png").Open())
                    {
                        var ms = new MemoryStream();
                        stream.CopyTo(ms);

                        GetPackCover(ms, ref pack);
                        ms.Dispose();
                    }
                    archive.Dispose();
                }
            }
            else
            {
                if (File.Exists(path + @"/pack.mcmeta"))
                {
                    GetPackInfo(File.ReadAllText(path + @"/pack.mcmeta", Encoding.UTF8), ref pack);
                }

                if (File.Exists(path + @"/pack.png"))
                {
                    var fs = File.Open(path + @"/pack.png", FileMode.Open);
                    GetPackCover(fs, ref pack);
                    fs.Dispose();
                }
            }

            return pack;

            void GetPackCover(Stream stream, ref ResPack _pack)
            {
                _pack.Cover = new BitmapImage();
                _pack.Cover.BeginInit();
                _pack.Cover.StreamSource = stream;
                _pack.Cover.DecodePixelWidth = 64;
                _pack.Cover.DecodePixelHeight = 64;
                _pack.Cover.CacheOption = BitmapCacheOption.OnLoad;
                _pack.Cover.EndInit();
                _pack.Cover.Freeze();
            }

            void GetPackInfo(string str, ref ResPack _pack)
            {
                var PackInfo = JsonMapper.ToObject(str)[0];
                _pack.Format = (int)PackInfo["pack_format"];

                string mcVersion = "适用版本:";

                switch(_pack.Format)
                {
                    case 1: mcVersion += "1.8及以下\n"; break;
                    case 2: mcVersion += "1.9-1.10\n"; break;
                    case 3: mcVersion += "1.11-1.12\n"; break;
                    case 4: mcVersion += "1.13"; break;
                    default: break;
                }

                _pack.Description = mcVersion + PackInfo["description"].ToString();
            }
        }

19 Source : ForgeInstall.xaml.cs
with MIT License
from Goose-Bomb

private async void InstallForgeAsync(object sender, RoutedEventArgs e)
        {
            if (_forgeList.SelectedIndex == -1)
            {
                MessageBox.Show("请选择要安装的Forge版本!", "(。•ˇ‸ˇ•。)", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            _downloadButton.IsEnabled = false;
            var core = App.Core;

            var forge = VersionForges[_forgeList.SelectedIndex];
            var forgeName = $"{_mcVersion}-{forge.Version}";
            var newVersionID = $"{_mcVersion}-forge{forgeName}";

            foreach(var version in Config.Args.Versions)
            {
                if(version.ID == newVersionID)
                {
                    MessageBox.Show($"{forgeName} 版本的forge已经安装!", "┑( ̄Д  ̄)┍");
                    return;
                }
            }

            var newVersionPath = $"{core.GameRootPath}\\versions\\{newVersionID}";
            var forgeJarPath = $"{core.GameRootPath}\\libraries\\net\\minecraftforge\\forge\\{forgeName}\\forge-{forgeName}.jar";

            var downloadName = forgeName + ((forge.Branch == null) ? null : $"-{forge.Branch}");
            var forgeDownload = new List<DownloadInfo>()
            {
                new DownloadInfo
                {
                    Path = forgeJarPath,
                    Url = $"{DownloadHelper.BaseUrl.ForgeBaseUrl}{downloadName}/forge-{downloadName}-universal.jar",
                }
            };

            var downloadPage = new Pages.DownloadPage();
            (Application.Current.MainWindow as MainWindow).Frame.Navigate(downloadPage);
            bool hasDownloadSucceeded = await downloadPage.StartDownloadAsync(forgeDownload, "下载Forge");

            if (!hasDownloadSucceeded)
            {
                MessageBox.Show($"下载 {_mcVersion} 版本Forge失败");
                _downloadButton.IsEnabled = true;
                return;
            }

            try
            {
                if (!Directory.Exists(newVersionPath))
                {
                    Directory.CreateDirectory(newVersionPath);
                }

                JsonData jsonData;
                string jsonText;

                using (var archive = ZipFile.OpenRead(forgeJarPath))
                {
                    var entry = archive.GetEntry("version.json");
                    using (var sr = new StreamReader(entry.Open(), System.Text.Encoding.UTF8))
                    {
                        jsonData = JsonMapper.ToObject(sr.ReadToEnd());
                    }
                }

                jsonData["id"] = newVersionID;
                jsonText = jsonData.ToJson();

                if (!jsonData.ContainsKey("inheritsFrom"))
                {
                    jsonText = jsonText.Substring(0, jsonText.Length - 1) + $",\"inheritsFrom\": \"{_mcVersion}\"}}";
                }

                File.WriteAllText($"{newVersionPath}\\{newVersionID}.json", jsonText, System.Text.Encoding.UTF8);
            }
            catch(Exception ex)
            {
                MessageBox.Show($"安装 {_mcVersion} 版本Forge失败\n{ex.Message}");
                _downloadButton.IsEnabled = true;
                return;
            }

            var newVersion = core.GetVersion(newVersionID);
            Config.Args.Versions.Add(newVersion);
            Config.Args.VersionIndex = Config.Args.Versions.IndexOf(newVersion);

            MessageBox.Show($"安装{_mcVersion}版本Forge成功");
            _downloadButton.IsEnabled = true;
        }

19 Source : Class1.cs
with GNU General Public License v3.0
from Hackplayers

public static Byte[] GetResourceInZip(ZipArchive zip, string resourceName)
        {
            foreach (var entry in zip.Entries)
            {
                if (entry.Name == resourceName)
                {
#if DEBUG
                    Console.WriteLine("Found {0} in zip", resourceName);
#endif
                    using (var resource = entry.Open())
                    {
                        var resdata = new Byte[entry.Length];
                        resource.Read(resdata, 0, resdata.Length);
                        return resdata;
                    }
                }
            }
            throw new Exception(String.Format("{0} not in zip file", resourceName));
        }

19 Source : LogFileZipper.cs
with MIT License
from ibiza240

private static byte[] Zip(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return new byte[0];

            using var stream = new MemoryStream();
            using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
            {
                ZipArchiveEntry manifest = archive.CreateEntry("Player.log");
                using Stream st = manifest.Open();
                using var writerManifest = new StreamWriter(st);
                writerManifest.Write(text);
            }

            return stream.ToArray();
        }

19 Source : ZipDeflator.cs
with MIT License
from ibiza240

public async Task<(OutputLogResult result, Guid? errorId, OutputLogResult2 outputLogResult2)> UnzipAndGetCollection(string userId, Stream fileStream)
        {
            if (fileStream == null)
                throw new ParseCollectionBaseException("No file provided");

            try
            {
                var archive = new ZipArchive(fileStream);

                if (archive.Entries.Count == 0)
                    throw new ParseCollectionEmptyZipContentException();

                if (archive.Entries.Count > 1)
                    throw new ParseCollectionZipContentMultipleFilesException();

                var entry = archive.Entries[0];

                var unzippedEntryStream = await Task.Run(() => entry.Open());
                return await reader.LoadFileContent(userId, unzippedEntryStream);
            }
            catch (InvalidDataException ex)
            {
                throw new ParseCollectionInvalidZipFileException(ex);
            }
        }

19 Source : Updater.cs
with GNU General Public License v3.0
from ic3w0lf22

private void Extract()
        {
            try
            {
                using (ZipArchive archive = ZipFile.OpenRead(FileName))
                {
                    foreach (ZipArchiveEntry newFile in archive.Entries)
                    {
                        string path = Path.Combine(Directory.GetCurrentDirectory(), newFile.Name);

                        if (newFile.Name == System.Reflection.replacedembly.GetExecutingreplacedembly().GetName().Name + ".exe") path = Path.Combine(Directory.GetCurrentDirectory(), "AU.exe");

                        if (File.Exists(path))
                        {
                            FileStream existingStream = File.OpenRead(path);
                            Stream newStream = newFile.Open();
                            string ExistingMD5 = GetMD5HashFromFile(existingStream);
                            string NewMD5 = GetMD5HashFromFile(newStream);

                            existingStream.Close();
                            newStream.Close();

                            if (ExistingMD5 != NewMD5)
                            {
                                try
                                {
                                    Console.WriteLine("Replacing " + path);
                                    File.Delete(path);
                                    newFile.ExtractToFile(path);
                                }
                                catch (Exception x)
                                {
                                    SetStatus("Error");
                                    Invoke(new Action(() => { MessageBox.Show(this, "Failed to extract file, make sure the alt manager is completely closed.\n" + x.Message); }));
                                    Environment.Exit(0);
                                }
                            }
                        }
                        else newFile.ExtractToFile(path);
                    }
                }
            } catch(Exception x)
            {
                SetStatus("Error");
                Invoke(new Action(() => { MessageBox.Show(this, "Something went wrong! " + x.Message); }));
                Environment.Exit(0);
            }

            SetStatus("Done!");
            Thread.Sleep(2500);
            File.Delete(FileName);

            if (File.Exists("RBX Alt Manager.exe"))
                Process.Start("RBX Alt Manager.exe");

            Environment.Exit(0);
        }

19 Source : ExtensionInstaller.cs
with MIT License
from JosefNemec

private static T GetPackedManifest<T>(string packagePath, string nanifestFileName) where T : clreplaced
        {
            using (var zip = ZipFile.OpenRead(packagePath))
            {
                var manifest = zip.GetEntry(nanifestFileName);
                if (manifest == null)
                {
                    return null;
                }

                using (var logStream = manifest.Open())
                {
                    using (TextReader tr = new StreamReader(logStream))
                    {
                        return Serialization.FromYaml<T>(tr.ReadToEnd());
                    }
                }
            }
        }

19 Source : ExtensionInstaller.cs
with MIT License
from JosefNemec

public static void VerifyExtensionPackage(string packagePath)
        {
            using (var zip = ZipFile.OpenRead(packagePath))
            {
                var manifestEntry = zip.GetEntry(PlaynitePaths.ExtensionManifestFileName);
                if (manifestEntry == null)
                {
                    logger.Error("Extension package is invalid, no manifest found.");
                    throw new LocalizedException(LOC.GeneralExtensionPackageError);
                }

                using (var logStream = manifestEntry.Open())
                {
                    using (TextReader tr = new StreamReader(logStream))
                    {
                        var manifest = Serialization.FromYaml<ExtensionManifest>(tr.ReadToEnd());
                        if (manifest.Id.IsNullOrEmpty())
                        {
                            logger.Error("Extension package is invalid, no extension ID found.");
                            throw new LocalizedException(LOC.GeneralExtensionPackageError);
                        }

                        if (!Version.TryParse(manifest.Version, out var _))
                        {
                            logger.Error($"Extension package is invalid, version is not in correct format {manifest.Version}.");
                            throw new LocalizedException(LOC.GeneralExtensionPackageError);
                        }
                    }
                }

                if (zip.Entries.Any(a => a.Name == "Playnite.dll" || a.Name == "Playnite.Common.dll"))
                {
                    logger.Error($"Extension package is invalid, includes not allowed Playnite dependencies.");
                    throw new LocalizedException(LOC.GeneralExtensionPackageError);
                }
            }
        }

See More Examples