using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using SabreTools.Library.Data; using SabreTools.Library.DatFiles; using SabreTools.Library.FileTypes; using SabreTools.Library.Skippers; namespace SabreTools.Library.IO { /// /// Extensions to File functionality /// public static class FileExtensions { /// /// Add an aribtrary number of bytes to the inputted file /// /// File to be appended to /// Outputted file /// Bytes to be added to head of file /// Bytes to be added to tail of file public static void AppendBytes(string input, string output, byte[] bytesToAddToHead, byte[] bytesToAddToTail) { // If any of the inputs are invalid, skip if (!File.Exists(input)) return; #if NET_FRAMEWORK using (FileStream fsr = TryOpenRead(input)) using (FileStream fsw = TryOpenWrite(output)) { #else using FileStream fsr = TryOpenRead(input); using FileStream fsw = TryOpenWrite(output); #endif StreamExtensions.AppendBytes(fsr, fsw, bytesToAddToHead, bytesToAddToTail); #if NET_FRAMEWORK } #endif } /// /// Get what type of DAT the input file is /// /// Name of the file to be parsed /// The DatFormat corresponding to the DAT public static DatFormat GetDatFormat(this string filename) { // Limit the output formats based on extension if (!PathExtensions.HasValidDatExtension(filename)) return 0; // Get the extension from the filename string ext = PathExtensions.GetNormalizedExtension(filename); // Read the input file, if possible Globals.Logger.Verbose($"Attempting to read file to get format: {filename}"); // Check if file exists if (!File.Exists(filename)) { Globals.Logger.Warning($"File '{filename}' could not read from!"); return 0; } // Some formats should only require the extension to know switch (ext) { case "csv": return DatFormat.CSV; case "json": return DatFormat.Json; case "md5": return DatFormat.RedumpMD5; #if NET_FRAMEWORK case "ripemd160": return DatFormat.RedumpRIPEMD160; #endif case "sfv": return DatFormat.RedumpSFV; case "sha1": return DatFormat.RedumpSHA1; case "sha256": return DatFormat.RedumpSHA256; case "sha384": return DatFormat.RedumpSHA384; case "sha512": return DatFormat.RedumpSHA512; case "spamsum": return DatFormat.RedumpSpamSum; case "ssv": return DatFormat.SSV; case "tsv": return DatFormat.TSV; } // For everything else, we need to read it try { // Get the first two non-whitespace, non-comment lines to check, if possible string first = string.Empty, second = string.Empty; try { using (StreamReader sr = File.OpenText(filename)) { first = sr.ReadLine().ToLowerInvariant(); while ((string.IsNullOrWhiteSpace(first) || first.StartsWith("