private bool ZipOneFile(string sourceFilePath, string entryName, string zipFilePath) { ZipArchive?zipArchive = null; bool result = true; try { zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Update); if (zipArchive.GetEntry(entryName) is null) { zipArchive.CreateEntryFromFile(sourceFilePath, entryName); } } catch (Exception e) { EventLogger.LogEvent($"Failed to Zip the File {sourceFilePath}. Error {e.Message}"); result = false; } finally { zipArchive?.Dispose(); } return(result); }
private static async Task <ZipArchive?> GetSnapshotAsync(string branch) { var status = $"Downloading repository snapshot ({branch} branch)..."; ZipArchive?result = null; try { await AnsiConsole .Status() .StartAsync(status, async ctx => { using var client = new WebClient(); client.DownloadProgressChanged += (_, eventArgs) => { ctx.Status($"{status}{eventArgs.BytesReceived / 1024}K"); }; var buffer = await client.DownloadDataTaskAsync(new Uri($"https://github.com/sailro/EscapeFromTarkov-Trainer/archive/refs/heads/{branch}.zip")); var stream = new MemoryStream(buffer); result = new ZipArchive(stream, ZipArchiveMode.Read); }); } catch (Exception ex) { AnsiConsole.MarkupLine(ex is WebException { Response: HttpWebResponse { StatusCode: HttpStatusCode.NotFound } } ? $"[yellow]Branch {branch} not found.[/]" : $"[red]Error: {ex.Message}[/]");
/// <summary> /// Creates backup of this audit trail. /// </summary> /// <param name="output">The stream used to store backup.</param> /// <param name="token">The token that can be used to cancel the operation.</param> /// <returns>A task representing state of asynchronous execution.</returns> /// <exception cref="OperationCanceledException">The operation has been canceled.</exception> public async Task CreateBackupAsync(Stream output, CancellationToken token = default) { ZipArchive?archive = null; await syncRoot.AcquireAsync(false, token).ConfigureAwait(false); try { archive = new ZipArchive(output, ZipArchiveMode.Create, true); foreach (var file in location.EnumerateFiles()) { await using var source = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, Buffer.Length, true); var entry = archive.CreateEntry(file.Name, backupCompression); entry.LastWriteTime = file.LastWriteTime; await using var destination = entry.Open(); await source.CopyToAsync(destination, token).ConfigureAwait(false); } await output.FlushAsync(token).ConfigureAwait(false); } finally { syncRoot.Release(); archive?.Dispose(); } }
public ZipContainerReader OpenFile(IWorkContext context) { _zipArchive.Verify().Assert(x => x == null, "Zip archive already opened"); File.Exists(FilePath).Verify(nameof(FilePath)).Assert(x => x == true, $"{FilePath} does not exist"); context.Telemetry.Info(context, $"Reading {FilePath}"); _zipArchive = ZipFile.Open(FilePath, ZipArchiveMode.Read); return(this); }
public static XDocument?GetEmbeddedPackageDataManifest(Type planType, out ZipArchive?zipArchive) { XDocument?packageXml; Stream? zipStream = GetEmbeddedPackageZipStream(planType); if (zipStream is not null) { zipArchive = GetPackageDataManifest(zipStream, out packageXml); return(packageXml); } zipArchive = null; packageXml = GetEmbeddedPackageXmlDoc(planType); return(packageXml); }
public ZipContainerWriter OpenFile(IWorkContext context) { _zipArchive.Verify().Assert(x => x == null, "Zip archive already opened"); Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); if (File.Exists(FilePath)) { context.Telemetry.Info(context, $"Deleting {FilePath}"); File.Delete(FilePath); } context.Telemetry.Info(context, $"Creating {FilePath}"); _zipArchive = ZipFile.Open(FilePath, ZipArchiveMode.Create); return(this); }
/// <summary> /// Internal constructor that is called by the OpenOnFile static method. /// </summary> /// <param name="path">File path to the container.</param> /// <param name="packageFileMode">Container is opened in the specified mode if possible</param> /// <param name="packageFileAccess">Container is opened with the specified access if possible</param> /// <param name="share">Container is opened with the specified share if possible</param> internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share) : base(packageFileAccess) { ZipArchive? zipArchive = null; ContentTypeHelper?contentTypeHelper; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; try { _containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share); _shouldCloseContainerStream = true; ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update; if (packageFileAccess == FileAccess.Read) { zipArchiveMode = ZipArchiveMode.Read; } else if (packageFileAccess == FileAccess.Write) { zipArchiveMode = ZipArchiveMode.Create; } else if (packageFileAccess == FileAccess.ReadWrite) { zipArchiveMode = ZipArchiveMode.Update; } zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8); _zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess); contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager); } catch { zipArchive?.Dispose(); _containerStream?.Dispose(); throw; } _zipArchive = zipArchive; _contentTypeHelper = contentTypeHelper; }
public ZipContainerReader(ZipArchive zipArchive) { zipArchive.Verify(nameof(zipArchive)).IsNotNull(); _zipArchive = zipArchive; }
public void Initialise() { _archive = new ZipArchive(_fileStream, ZipArchiveMode.Read, true); _archiveEntries = _archive.Entries; }
/// <summary> /// Internal constructor that is called by the Open(Stream) static methods. /// </summary> /// <param name="s"></param> /// <param name="packageFileMode"></param> /// <param name="packageFileAccess"></param> internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess) : base(packageFileAccess) { ZipArchive? zipArchive = null; ContentTypeHelper?contentTypeHelper; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; try { if (s.CanSeek) { switch (packageFileMode) { case FileMode.Open: if (s.Length == 0) { throw new FileFormatException(SR.ZipZeroSizeFileIsNotValidArchive); } break; case FileMode.CreateNew: if (s.Length != 0) { throw new IOException(SR.CreateNewOnNonEmptyStream); } break; case FileMode.Create: if (s.Length != 0) { s.SetLength(0); // Discard existing data } break; } } ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update; if (packageFileAccess == FileAccess.Read) { zipArchiveMode = ZipArchiveMode.Read; } else if (packageFileAccess == FileAccess.Write) { zipArchiveMode = ZipArchiveMode.Create; } else if (packageFileAccess == FileAccess.ReadWrite) { zipArchiveMode = ZipArchiveMode.Update; } zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8); _zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess); contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager); } catch (InvalidDataException) { throw new FileFormatException(SR.FileContainsCorruptedData); } catch { zipArchive?.Dispose(); throw; } _containerStream = s; _shouldCloseContainerStream = false; _zipArchive = zipArchive; _contentTypeHelper = contentTypeHelper; }
/// <inheritdoc/> public HashResult HashZippedBeatmap(string zipPath, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(zipPath)) { throw new ArgumentNullException(nameof(zipPath)); } if (cancellationToken.IsCancellationRequested) { return(HashResult.AsCanceled); } bool missingDiffs = false; string?message = null; if (!File.Exists(zipPath)) { return(new HashResult(null, $"File doesn't exist: '{zipPath}'", new FileNotFoundException($"File doesn't exist: '{zipPath}'"))); } ZipArchive?zip = null; try { try { zip = ZipFile.OpenRead(zipPath); } catch (Exception ex) { return(new HashResult(null, $"Unable to hash beatmap zip '{zipPath}': {ex.Message}", ex)); } ZipArchiveEntry?infoFile = zip.Entries.FirstOrDefault(e => e.FullName.Equals("info.dat", StringComparison.OrdinalIgnoreCase)); if (infoFile == null) { return(new HashResult(null, $"Could not find 'info.dat' file in '{zipPath}'", null)); } JObject?token = null; using (Stream info = infoFile.Open()) using (StreamReader reader = new StreamReader(info)) using (JsonTextReader jsonReader = new JsonTextReader(reader)) { token = JsonSerializer.Deserialize <JObject>(jsonReader); } if (token == null) { return(new HashResult(null, $"Could not read 'info.dat' file in '{zipPath}'", null)); } if (cancellationToken.IsCancellationRequested) { return(HashResult.AsCanceled); } using Stream infoStream = infoFile.Open(); string[] beatmapFiles = Utilities.GetDifficultyFileNames(token).ToArray(); using ConcatenatedStream streams = new ConcatenatedStream(beatmapFiles.Length + 1); streams.Append(infoStream); for (int i = 0; i < beatmapFiles.Length; i++) { if (cancellationToken.IsCancellationRequested) { return(HashResult.AsCanceled); } ZipArchiveEntry?diff = zip.Entries.FirstOrDefault(e => e.FullName.Equals(beatmapFiles[i], StringComparison.OrdinalIgnoreCase)); if (diff == null) { if (missingDiffs == false) { message = $"Could not find difficulty file '{beatmapFiles[i]}' in '{zipPath}'"; } else { message = $"Missing multiple difficulty files in '{zipPath}'"; } missingDiffs = true; continue; } streams.Append(diff.Open()); } if (cancellationToken.IsCancellationRequested) { return(HashResult.AsCanceled); } string?hash = null; if (streams.StreamCount > 0) { hash = Utilities.CreateSha1FromStream(streams); } return(new HashResult(hash, message, null)); } catch (Exception ex) { return(new HashResult(null, $"Error hashing '{zipPath}'", ex)); } finally { zip?.Dispose(); } }
public static void Save(Dictionary <int, ushort> characterToGlyphMap, SKTypeface typeface, float textSize, string fill, string outputDirectory, ZipArchive?zipArchive) { var skColor = new SKColor(0x00, 0x00, 0x00); using var skTextPaint = new SKPaint { IsAntialias = true, Color = skColor, Typeface = typeface, TextEncoding = SKTextEncoding.Utf32, TextSize = textSize, TextAlign = SKTextAlign.Center, LcdRenderText = true, SubpixelText = true }; var metrics = skTextPaint.FontMetrics; var mAscent = metrics.Ascent; var mDescent = metrics.Descent; foreach (var kvp in characterToGlyphMap) { var charCode = kvp.Key; var utf32 = Char.ConvertFromUtf32((int)charCode); float x = 0; float y = (mAscent / 2.0f) - mDescent / 2.0f; using var outlinePath = skTextPaint.GetTextPath(utf32, x, y); using var fillPath = skTextPaint.GetFillPath(outlinePath); fillPath.Transform(SKMatrix.CreateTranslation(-fillPath.Bounds.Left, -fillPath.Bounds.Top)); var bounds = fillPath.Bounds; var svgPathData = fillPath.ToSvgPathData(); var sb = new StringBuilder(); sb.AppendLine($"<svg viewBox=\"{bounds.Left} {bounds.Top} {bounds.Width} {bounds.Height}\" xmlns=\"http://www.w3.org/2000/svg\">"); // width=\"{bounds.Width}\" height=\"{bounds.Height}\" sb.AppendLine($" <path fill=\"{fill}\" d=\"{svgPathData}\"/>"); sb.AppendLine($"</svg>"); var svg = sb.ToString(); var outputPath = Path.Combine(outputDirectory, $"{charCode.ToString("X2").PadLeft(5, '0')}_{typeface.FamilyName}.svg"); if (zipArchive != null) { var zipArchiveEntry = zipArchive.CreateEntry(outputPath); using var streamWriter = new StreamWriter(zipArchiveEntry.Open()); streamWriter.Write(svg); } else { using var streamWriter = File.CreateText(outputPath); streamWriter.Write(svg); } } }
private async Task <bool> InitializeDataInternal() { Stream? scrapeStream = null; Stream? jsonStream = null; ZipArchive?zip = null; List <OldAndruzzScrapedSong>?songList = null; try { if (FilePath != null && File.Exists(FilePath)) { try { jsonStream = File.OpenRead(FilePath); songList = ParseJson(jsonStream); Logger?.Debug($"{songList?.Count ?? 0} songs data loaded from '{FilePath}'"); } catch (Exception ex) { Logger?.Warning($"Error reading song info json file at '{FilePath}': {ex.Message}"); } } if (songList == null || songList.Count == 0) { try { WebUtilities.IWebResponseMessage?downloadResponse = await WebUtils.WebClient.GetAsync(ScrapedDataUrl).ConfigureAwait(false); downloadResponse.EnsureSuccessStatusCode(); if (downloadResponse.Content != null) { scrapeStream = await downloadResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); zip = new ZipArchive(scrapeStream, ZipArchiveMode.Read); jsonStream = zip.GetEntry(dataFileName).Open(); songList = ParseJson(jsonStream); Logger?.Debug($"{songList?.Count ?? 0} songs data loaded from GitHub."); } } catch (Exception ex) { Logger?.Warning($"Error loading Andruzz's Scrapped Data from GitHub: {ex.Message}"); } } if (songList != null) { foreach (OldAndruzzScrapedSong?song in songList) { if (song.Hash != null) { _byHash[song.Hash] = song; } if (song.Key != null) { _byKey[song.Key] = song; } } } else { Logger?.Warning("Unable to load Andruzz's Scrapped Data."); } } catch (Exception ex) { Logger?.Warning($"Error loading Andruzz's Scrapped Data: {ex.Message}"); } finally { jsonStream?.Dispose(); zip?.Dispose(); scrapeStream?.Dispose(); } return(true); }