[ALL] One utility class now

This commit is contained in:
Matt Nadareski
2017-11-08 00:27:00 -08:00
parent 65ef5785ef
commit 5dd08cba63
40 changed files with 1014 additions and 1037 deletions

View File

@@ -64,14 +64,14 @@ namespace RombaSharp
{
Process proc = Process.GetCurrentProcess();
Globals.Logger.User("Current Nonpaged Memory: {0}", Style.GetBytesReadable(proc.NonpagedSystemMemorySize64));
Globals.Logger.User("Current Paged Memory: {0}", Style.GetBytesReadable(proc.PagedMemorySize64));
Globals.Logger.User("Peak Paged Memory: {0}", Style.GetBytesReadable(proc.PeakPagedMemorySize64));
Globals.Logger.User("Peak Virtual Memory: {0}", Style.GetBytesReadable(proc.PeakVirtualMemorySize64));
Globals.Logger.User("Peak Working Memory: {0}", Style.GetBytesReadable(proc.PeakWorkingSet64));
Globals.Logger.User("Private Memory: {0}", Style.GetBytesReadable(proc.PrivateMemorySize64));
Globals.Logger.User("Virtual Memory: {0}", Style.GetBytesReadable(proc.VirtualMemorySize64));
Globals.Logger.User("Working Memory: {0}", Style.GetBytesReadable(proc.WorkingSet64));
Globals.Logger.User("Current Nonpaged Memory: {0}", Utilities.GetBytesReadable(proc.NonpagedSystemMemorySize64));
Globals.Logger.User("Current Paged Memory: {0}", Utilities.GetBytesReadable(proc.PagedMemorySize64));
Globals.Logger.User("Peak Paged Memory: {0}", Utilities.GetBytesReadable(proc.PeakPagedMemorySize64));
Globals.Logger.User("Peak Virtual Memory: {0}", Utilities.GetBytesReadable(proc.PeakVirtualMemorySize64));
Globals.Logger.User("Peak Working Memory: {0}", Utilities.GetBytesReadable(proc.PeakWorkingSet64));
Globals.Logger.User("Private Memory: {0}", Utilities.GetBytesReadable(proc.PrivateMemorySize64));
Globals.Logger.User("Virtual Memory: {0}", Utilities.GetBytesReadable(proc.VirtualMemorySize64));
Globals.Logger.User("Working Memory: {0}", Utilities.GetBytesReadable(proc.WorkingSet64));
Globals.Logger.User("Total Processor Time: {0}", proc.TotalProcessorTime);
Globals.Logger.User("User Processor Time: {0}", proc.UserProcessorTime);
}
@@ -84,7 +84,7 @@ namespace RombaSharp
{
SqliteConnection dbc = new SqliteConnection(_connectionString);
dbc.Open();
StreamWriter sw = new StreamWriter(FileTools.TryCreate("export.csv"));
StreamWriter sw = new StreamWriter(Utilities.TryCreate("export.csv"));
sw.WriteLine("\"ID\",\"Size\",\"CRC\",\"MD5\",\"SHA-1\",\"In Depot\",\"DAT Hash\"");
@@ -129,7 +129,7 @@ namespace RombaSharp
if (lowerCaseDats.Contains(input.ToLowerInvariant()))
{
string fullpath = Path.GetFullPath(datRootDats[lowerCaseDats.IndexOf(input.ToLowerInvariant())]);
string sha1 = ((Rom)FileTools.GetFileInfo(fullpath)).SHA1;
string sha1 = ((Rom)Utilities.GetFileInfo(fullpath)).SHA1;
foundDats.Add(sha1, fullpath);
}
else
@@ -161,7 +161,7 @@ namespace RombaSharp
Dictionary<string, Tuple<long, bool>> depots = new Dictionary<string, Tuple<long, bool>>();
// Get the XML text reader for the configuration file, if possible
XmlReader xtr = FileTools.GetXmlTextReader(_config);
XmlReader xtr = Utilities.GetXmlTextReader(_config);
// Now parse the XML file for settings
if (xtr != null)

View File

@@ -175,7 +175,7 @@ namespace RombaSharp
}
// Create the sorting object to use and rebuild the needed files
ArchiveScanLevel asl = FileTools.GetArchiveScanLevelFromNumbers((onlyNeeded ? 0 : 1), (onlyNeeded ? 0 : 1), (onlyNeeded ? 0 : 1), (onlyNeeded ? 0 : 1));
ArchiveScanLevel asl = Utilities.GetArchiveScanLevelFromNumbers((onlyNeeded ? 0 : 1), (onlyNeeded ? 0 : 1), (onlyNeeded ? 0 : 1), (onlyNeeded ? 0 : 1));
need.RebuildGeneric(onlyDirs, _depots.Keys.ToList()[0], false /*quickScan*/, false /*date*/,
false /*delete*/, false /*inverse*/, OutputFormat.TorrentGzip, true /*romba*/, asl, false /*updateDat*/,
null /*headerToCheckAgainst*/, true /* chdsAsFiles */);
@@ -215,7 +215,7 @@ namespace RombaSharp
List<string> onlineDepots = _depots.Where(d => d.Value.Item2).Select(d => d.Key).ToList();
// Now scan all of those depots and rebuild
ArchiveScanLevel asl = FileTools.GetArchiveScanLevelFromNumbers(1, 1, 1, 1);
ArchiveScanLevel asl = Utilities.GetArchiveScanLevelFromNumbers(1, 1, 1, 1);
datFile.RebuildDepot(onlineDepots, outputFolder, false /*date*/,
false /*delete*/, false /*inverse*/, (copy ? OutputFormat.TorrentGzip : OutputFormat.TorrentZip), copy,
false /*updateDat*/, null /*headerToCheckAgainst*/);
@@ -300,7 +300,7 @@ namespace RombaSharp
string temp = "";
if (input.Length == Constants.CRCLength)
{
temp = Style.CleanHashData(input, Constants.CRCLength);
temp = Utilities.CleanHashData(input, Constants.CRCLength);
if (temp != "")
{
crc.Add(temp);
@@ -308,7 +308,7 @@ namespace RombaSharp
}
else if (input.Length == Constants.MD5Length)
{
temp = Style.CleanHashData(input, Constants.MD5Length);
temp = Utilities.CleanHashData(input, Constants.MD5Length);
if (temp != "")
{
md5.Add(temp);
@@ -316,7 +316,7 @@ namespace RombaSharp
}
else if (input.Length == Constants.SHA1Length)
{
temp = Style.CleanHashData(input, Constants.SHA1Length);
temp = Utilities.CleanHashData(input, Constants.SHA1Length);
if (temp != "")
{
sha1.Add(temp);

View File

@@ -58,8 +58,8 @@ namespace SabreTools.Library.DatFiles
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
Encoding enc = Utilities.GetEncoding(filename);
StreamReader sr = new StreamReader(Utilities.TryOpenRead(filename), enc);
sr.ReadLine(); // Skip the first line since it's the header
while (!sr.EndOfStream)
@@ -123,7 +123,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -59,8 +59,8 @@ namespace SabreTools.Library.DatFiles
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
Encoding enc = Utilities.GetEncoding(filename);
StreamReader sr = new StreamReader(Utilities.TryOpenRead(filename), enc);
bool block = false, superdat = false;
string blockname = "", tempgamename = "", gamedesc = "", cloneof = "",
@@ -163,7 +163,7 @@ namespace SabreTools.Library.DatFiles
}
// Get the line split by spaces and quotes
string[] gc = Style.SplitLineAsCMP(line);
string[] gc = Utilities.SplitLineAsCMP(line);
// Special cases for DOSCenter DATs only because of how the lines are arranged
if (line.Trim().StartsWith("file ("))
@@ -636,7 +636,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -1611,7 +1611,7 @@ namespace SabreTools.Library.DatFiles
&& (updateMode & UpdateMode.ReverseBaseReplace) == 0)
{
// Make sure there are no folders in inputs
List<string> newInputFileNames = FileTools.GetOnlyFilesFromInputs(inputPaths, appendparent: true);
List<string> newInputFileNames = Utilities.GetOnlyFilesFromInputs(inputPaths, appendparent: true);
// Reverse if we have to
if ((updateMode & UpdateMode.DiffReverseCascade) != 0)
@@ -1748,7 +1748,7 @@ namespace SabreTools.Library.DatFiles
// First we want to parse all of the base DATs into the input
InternalStopwatch watch = new InternalStopwatch("Populating base DAT for replacement...");
List<string> baseFileNames = FileTools.GetOnlyFilesFromInputs(basePaths);
List<string> baseFileNames = Utilities.GetOnlyFilesFromInputs(basePaths);
Parallel.For(0, baseFileNames.Count, Globals.ParallelOptions, i =>
{
string path = "";
@@ -1769,7 +1769,7 @@ namespace SabreTools.Library.DatFiles
BucketBy(SortedBy.CRC, DedupeType.Full);
// Now we want to try to replace each item in each input DAT from the base
List<string> inputFileNames = FileTools.GetOnlyFilesFromInputs(inputPaths, appendparent: true);
List<string> inputFileNames = Utilities.GetOnlyFilesFromInputs(inputPaths, appendparent: true);
foreach (string path in inputFileNames)
{
// Get the two halves of the path
@@ -1866,7 +1866,7 @@ namespace SabreTools.Library.DatFiles
// First we want to parse all of the base DATs into the input
InternalStopwatch watch = new InternalStopwatch("Populating base DAT for comparison...");
List<string> baseFileNames = FileTools.GetOnlyFilesFromInputs(basePaths);
List<string> baseFileNames = Utilities.GetOnlyFilesFromInputs(basePaths);
Parallel.ForEach(baseFileNames, Globals.ParallelOptions, path =>
{
Parse(path, 0, 0, keep: true, clean: clean, remUnicode: remUnicode, descAsName: descAsName);
@@ -1878,7 +1878,7 @@ namespace SabreTools.Library.DatFiles
BucketBy(SortedBy.CRC, DedupeType.Full);
// Now we want to compare each input DAT against the base
List<string> inputFileNames = FileTools.GetOnlyFilesFromInputs(inputPaths, appendparent: true);
List<string> inputFileNames = Utilities.GetOnlyFilesFromInputs(inputPaths, appendparent: true);
foreach (string path in inputFileNames)
{
// Get the two halves of the path
@@ -3178,12 +3178,12 @@ namespace SabreTools.Library.DatFiles
FileName = (String.IsNullOrEmpty(FileName) ? (keepext ? Path.GetFileName(filename) : Path.GetFileNameWithoutExtension(filename)) : FileName);
// If the output type isn't set already, get the internal output type
DatFormat = (DatFormat == 0 ? FileTools.GetDatFormat(filename) : DatFormat);
DatFormat = (DatFormat == 0 ? Utilities.GetDatFormat(filename) : DatFormat);
// Now parse the correct type of DAT
try
{
switch (FileTools.GetDatFormat(filename))
switch (Utilities.GetDatFormat(filename))
{
case DatFormat.AttractMode:
new AttractMode(this).Parse(filename, sysid, srcid, keep, clean, remUnicode);
@@ -3324,14 +3324,14 @@ namespace SabreTools.Library.DatFiles
}
// If we're in cleaning mode, sanitize the game name
item.MachineName = (clean ? Style.CleanGameName(item.MachineName) : item.MachineName);
item.MachineName = (clean ? Utilities.CleanGameName(item.MachineName) : item.MachineName);
// If we're stripping unicode characters, do so from all relevant things
if (remUnicode)
{
item.Name = Style.RemoveUnicodeCharacters(item.Name);
item.MachineName = Style.RemoveUnicodeCharacters(item.MachineName);
item.MachineDescription = Style.RemoveUnicodeCharacters(item.MachineDescription);
item.Name = Utilities.RemoveUnicodeCharacters(item.Name);
item.MachineName = Utilities.RemoveUnicodeCharacters(item.MachineName);
item.MachineDescription = Utilities.RemoveUnicodeCharacters(item.MachineDescription);
}
// If we have a Rom or a Disk, clean the hash data
@@ -3340,12 +3340,12 @@ namespace SabreTools.Library.DatFiles
Rom itemRom = (Rom)item;
// Sanitize the hashes from null, hex sizes, and "true blank" strings
itemRom.CRC = Style.CleanHashData(itemRom.CRC, Constants.CRCLength);
itemRom.MD5 = Style.CleanHashData(itemRom.MD5, Constants.MD5Length);
itemRom.SHA1 = Style.CleanHashData(itemRom.SHA1, Constants.SHA1Length);
itemRom.SHA256 = Style.CleanHashData(itemRom.SHA256, Constants.SHA256Length);
itemRom.SHA384 = Style.CleanHashData(itemRom.SHA384, Constants.SHA384Length);
itemRom.SHA512 = Style.CleanHashData(itemRom.SHA512, Constants.SHA512Length);
itemRom.CRC = Utilities.CleanHashData(itemRom.CRC, Constants.CRCLength);
itemRom.MD5 = Utilities.CleanHashData(itemRom.MD5, Constants.MD5Length);
itemRom.SHA1 = Utilities.CleanHashData(itemRom.SHA1, Constants.SHA1Length);
itemRom.SHA256 = Utilities.CleanHashData(itemRom.SHA256, Constants.SHA256Length);
itemRom.SHA384 = Utilities.CleanHashData(itemRom.SHA384, Constants.SHA384Length);
itemRom.SHA512 = Utilities.CleanHashData(itemRom.SHA512, Constants.SHA512Length);
// If we have a rom and it's missing size AND the hashes match a 0-byte file, fill in the rest of the info
if ((itemRom.Size == 0 || itemRom.Size == -1)
@@ -3395,11 +3395,11 @@ namespace SabreTools.Library.DatFiles
Disk itemDisk = (Disk)item;
// Sanitize the hashes from null, hex sizes, and "true blank" strings
itemDisk.MD5 = Style.CleanHashData(itemDisk.MD5, Constants.MD5Length);
itemDisk.SHA1 = Style.CleanHashData(itemDisk.SHA1, Constants.SHA1Length);
itemDisk.SHA256 = Style.CleanHashData(itemDisk.SHA256, Constants.SHA256Length);
itemDisk.SHA384 = Style.CleanHashData(itemDisk.SHA384, Constants.SHA384Length);
itemDisk.SHA512 = Style.CleanHashData(itemDisk.SHA512, Constants.SHA512Length);
itemDisk.MD5 = Utilities.CleanHashData(itemDisk.MD5, Constants.MD5Length);
itemDisk.SHA1 = Utilities.CleanHashData(itemDisk.SHA1, Constants.SHA1Length);
itemDisk.SHA256 = Utilities.CleanHashData(itemDisk.SHA256, Constants.SHA256Length);
itemDisk.SHA384 = Utilities.CleanHashData(itemDisk.SHA384, Constants.SHA384Length);
itemDisk.SHA512 = Utilities.CleanHashData(itemDisk.SHA512, Constants.SHA512Length);
// If the file has aboslutely no hashes, skip and log
if (itemDisk.ItemStatus != ItemStatus.Nodump
@@ -3523,7 +3523,7 @@ namespace SabreTools.Library.DatFiles
// Now find all folders that are empty, if we are supposed to
if (!Romba && addBlanks)
{
List<string> empties = FileTools.GetEmptyDirectories(basePath).ToList();
List<string> empties = Utilities.GetEmptyDirectories(basePath).ToList();
Parallel.ForEach(empties, Globals.ParallelOptions, dir =>
{
// Get the full path for the directory
@@ -3580,7 +3580,7 @@ namespace SabreTools.Library.DatFiles
Globals.Logger.User("Cleaning temp folder");
if (tempDir != Path.GetTempPath())
{
FileTools.TryDeleteDirectory(tempDir);
Utilities.TryDeleteDirectory(tempDir);
}
return true;
@@ -3647,7 +3647,7 @@ namespace SabreTools.Library.DatFiles
if (!archivesAsFiles)
{
// Get the base archive first
BaseArchive archive = FileTools.CreateArchiveFromExistingInput(newItem);
BaseArchive archive = Utilities.CreateArchiveFromExistingInput(newItem);
// Now get all extracted items from the archive
if (archive != null)
@@ -3686,7 +3686,7 @@ namespace SabreTools.Library.DatFiles
List<string> empties = new List<string>();
// Get the base archive first
BaseArchive archive = FileTools.CreateArchiveFromExistingInput(newItem);
BaseArchive archive = Utilities.CreateArchiveFromExistingInput(newItem);
// Now get all blank folders from the archive
if (archive != null)
@@ -3709,11 +3709,11 @@ namespace SabreTools.Library.DatFiles
// Cue to delete the file if it's a copy
if (copyFiles && item != newItem)
{
FileTools.TryDeleteDirectory(newBasePath);
Utilities.TryDeleteDirectory(newBasePath);
}
// Delete the sub temp directory
FileTools.TryDeleteDirectory(tempSubDir);
Utilities.TryDeleteDirectory(tempSubDir);
}
/// <summary>
@@ -3730,7 +3730,7 @@ namespace SabreTools.Library.DatFiles
bool addDate, string headerToCheckAgainst, bool chdsAsFiles)
{
Globals.Logger.Verbose("'{0}' treated like a file", Path.GetFileName(item));
DatItem datItem = FileTools.GetFileInfo(item, omitFromScan: omitFromScan, date: addDate, header: headerToCheckAgainst, chdsAsFiles: chdsAsFiles);
DatItem datItem = Utilities.GetFileInfo(item, omitFromScan: omitFromScan, date: addDate, header: headerToCheckAgainst, chdsAsFiles: chdsAsFiles);
ProcessFileHelper(item, datItem, basePath, parent);
}
@@ -3991,7 +3991,7 @@ namespace SabreTools.Library.DatFiles
Globals.Logger.User("Checking hash '{0}'", hash);
// Get the extension path for the hash
string subpath = Style.GetRombaPath(hash);
string subpath = Utilities.GetRombaPath(hash);
// Find the first depot that includes the hash
string foundpath = null;
@@ -4203,13 +4203,13 @@ namespace SabreTools.Library.DatFiles
bool usedInternally = false;
// Get the required scanning level for the file
FileTools.GetInternalExternalProcess(file, archiveScanLevel, out bool shouldExternalProcess, out bool shouldInternalProcess);
Utilities.GetInternalExternalProcess(file, archiveScanLevel, out bool shouldExternalProcess, out bool shouldInternalProcess);
// If we're supposed to scan the file externally
if (shouldExternalProcess)
{
// TODO: All instances of Hash.DeepHashes should be made into 0x0 eventually
DatItem fileinfo = FileTools.GetFileInfo(file, omitFromScan: (quickScan ? Hash.SecureHashes : Hash.DeepHashes),
DatItem fileinfo = Utilities.GetFileInfo(file, omitFromScan: (quickScan ? Hash.SecureHashes : Hash.DeepHashes),
header: headerToCheckAgainst, chdsAsFiles: chdsAsFiles);
usedExternally = RebuildIndividualFile(fileinfo, file, outDir, date, inverse, outputFormat,
romba, updateDat, null /* isZip */, headerToCheckAgainst);
@@ -4227,7 +4227,7 @@ namespace SabreTools.Library.DatFiles
bool isTorrentGzip = tgz.IsTorrent();
// Get the base archive first
BaseArchive archive = FileTools.CreateArchiveFromExistingInput(file);
BaseArchive archive = Utilities.CreateArchiveFromExistingInput(file);
// Now get all extracted items from the archive
if (archive != null)
@@ -4240,7 +4240,7 @@ namespace SabreTools.Library.DatFiles
if (entries == null && File.Exists(file))
{
// TODO: All instances of Hash.DeepHashes should be made into 0x0 eventually
DatItem fileinfo = FileTools.GetFileInfo(file, omitFromScan: (quickScan ? Hash.SecureHashes : Hash.DeepHashes), chdsAsFiles: chdsAsFiles);
DatItem fileinfo = Utilities.GetFileInfo(file, omitFromScan: (quickScan ? Hash.SecureHashes : Hash.DeepHashes), chdsAsFiles: chdsAsFiles);
usedExternally = RebuildIndividualFile(fileinfo, file, outDir, date, inverse, outputFormat,
romba, updateDat, null /* isZip */, headerToCheckAgainst);
}
@@ -4258,7 +4258,7 @@ namespace SabreTools.Library.DatFiles
// If we are supposed to delete the file, do so
if (delete && (usedExternally || usedInternally))
{
FileTools.TryDeleteFile(file);
Utilities.TryDeleteFile(file);
}
}
@@ -4325,7 +4325,7 @@ namespace SabreTools.Library.DatFiles
// Get the proper output path
if (romba)
{
outDir = Path.Combine(outDir, Style.GetRombaPath(sha1));
outDir = Path.Combine(outDir, Utilities.GetRombaPath(sha1));
}
else
{
@@ -4356,7 +4356,7 @@ namespace SabreTools.Library.DatFiles
if (isZip != null)
{
string realName = null;
BaseArchive archive = FileTools.CreateArchiveFromExistingInput(file);
BaseArchive archive = Utilities.CreateArchiveFromExistingInput(file);
if (archive != null)
{
(fileStream, realName) = archive.ExtractEntryStream(datItem.Name);
@@ -4365,7 +4365,7 @@ namespace SabreTools.Library.DatFiles
// Otherwise, just open the filestream
else
{
fileStream = FileTools.TryOpenRead(file);
fileStream = Utilities.TryOpenRead(file);
}
// If the stream is null, then continue
@@ -4384,7 +4384,7 @@ namespace SabreTools.Library.DatFiles
foreach (DatItem item in dupes)
{
// Get the output archive, if possible
BaseArchive outputArchive = FileTools.CreateArchiveFromOutputFormat(outputFormat);
BaseArchive outputArchive = Utilities.CreateArchiveFromOutputFormat(outputFormat);
// Now rebuild to the output file
outputArchive.Write(fileStream, outDir, (Rom)item, date: date, romba: romba);
@@ -4407,7 +4407,7 @@ namespace SabreTools.Library.DatFiles
// Get the proper output path
if (romba)
{
outDir = Path.Combine(outDir, Style.GetRombaPath(sha1));
outDir = Path.Combine(outDir, Utilities.GetRombaPath(sha1));
}
else
{
@@ -4438,7 +4438,7 @@ namespace SabreTools.Library.DatFiles
if (isZip != null)
{
string realName = null;
BaseArchive archive = FileTools.CreateArchiveFromExistingInput(file);
BaseArchive archive = Utilities.CreateArchiveFromExistingInput(file);
if (archive != null)
{
(fileStream, realName) = archive.ExtractEntryStream(datItem.Name);
@@ -4447,7 +4447,7 @@ namespace SabreTools.Library.DatFiles
// Otherwise, just open the filestream
else
{
fileStream = FileTools.TryOpenRead(file);
fileStream = Utilities.TryOpenRead(file);
}
// If the stream is null, then continue
@@ -4457,7 +4457,7 @@ namespace SabreTools.Library.DatFiles
}
// Get the item from the current file
Rom item = (Rom)FileTools.GetStreamInfo(fileStream, fileStream.Length, keepReadOpen: true);
Rom item = (Rom)Utilities.GetStreamInfo(fileStream, fileStream.Length, keepReadOpen: true);
item.MachineName = Path.GetFileNameWithoutExtension(item.Name);
item.MachineDescription = Path.GetFileNameWithoutExtension(item.Name);
@@ -4471,12 +4471,12 @@ namespace SabreTools.Library.DatFiles
Globals.Logger.User("No matches found for '{0}', rebuilding accordingly from inverse flag...", Path.GetFileName(datItem.Name));
// Get the output archive, if possible
BaseArchive outputArchive = FileTools.CreateArchiveFromOutputFormat(outputFormat);
BaseArchive outputArchive = Utilities.CreateArchiveFromOutputFormat(outputFormat);
// Now rebuild to the output file
if (outputArchive == null)
{
string outfile = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(item.MachineName), item.Name);
string outfile = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(item.MachineName), item.Name);
// Make sure the output folder is created
Directory.CreateDirectory(Path.GetDirectoryName(outfile));
@@ -4484,7 +4484,7 @@ namespace SabreTools.Library.DatFiles
// Now copy the file over
try
{
FileStream writeStream = FileTools.TryCreate(outfile);
FileStream writeStream = Utilities.TryCreate(outfile);
// Copy the input stream to the output
int bufferSize = 4096 * 128;
@@ -4528,7 +4528,7 @@ namespace SabreTools.Library.DatFiles
if (isZip != null)
{
string realName = null;
BaseArchive archive = FileTools.CreateArchiveFromExistingInput(file);
BaseArchive archive = Utilities.CreateArchiveFromExistingInput(file);
if (archive != null)
{
(fileStream, realName) = archive.ExtractEntryStream(datItem.Name);
@@ -4537,7 +4537,7 @@ namespace SabreTools.Library.DatFiles
// Otherwise, just open the filestream
else
{
fileStream = FileTools.TryOpenRead(file);
fileStream = Utilities.TryOpenRead(file);
}
// If the stream is null, then continue
@@ -4557,7 +4557,7 @@ namespace SabreTools.Library.DatFiles
if (rule.TransformStream(fileStream, transformStream, keepReadOpen: true, keepWriteOpen: true))
{
// Get the file informations that we will be using
Rom headerless = (Rom)FileTools.GetStreamInfo(transformStream, transformStream.Length, keepReadOpen: true);
Rom headerless = (Rom)Utilities.GetStreamInfo(transformStream, transformStream.Length, keepReadOpen: true);
// Find if the file has duplicates in the DAT
hasDuplicates = headerless.HasDuplicates(this);
@@ -4588,7 +4588,7 @@ namespace SabreTools.Library.DatFiles
bool eitherSuccess = false;
// Get the output archive, if possible
BaseArchive outputArchive = FileTools.CreateArchiveFromOutputFormat(outputFormat);
BaseArchive outputArchive = Utilities.CreateArchiveFromOutputFormat(outputFormat);
// Now rebuild to the output file
eitherSuccess |= outputArchive.Write(transformStream, outDir, (Rom)item, date: date, romba: romba);
@@ -4657,7 +4657,7 @@ namespace SabreTools.Library.DatFiles
Globals.Logger.User("Checking hash '{0}'", hash);
// Get the extension path for the hash
string subpath = Style.GetRombaPath(hash);
string subpath = Utilities.GetRombaPath(hash);
// Find the first depot that includes the hash
string foundpath = null;
@@ -5416,7 +5416,7 @@ namespace SabreTools.Library.DatFiles
// Log the results to screen
string results = @"For '" + FileName + @"':
--------------------------------------------------
Uncompressed size: " + Style.GetBytesReadable(TotalSize) + @"
Uncompressed size: " + Utilities.GetBytesReadable(TotalSize) + @"
Games found: " + (game == -1 ? Keys.Count() : game) + @"
Roms found: " + RomCount + @"
Disks found: " + DiskCount + @"
@@ -5900,7 +5900,7 @@ namespace SabreTools.Library.DatFiles
Dictionary<StatReportFormat, string> outputs = CreateOutStatsNames(outDir, statDatFormat, reportName);
// Make sure we have all files and then order them
List<string> files = FileTools.GetOnlyFilesFromInputs(inputs);
List<string> files = Utilities.GetOnlyFilesFromInputs(inputs);
files = files
.OrderBy(i => Path.GetDirectoryName(i))
.ThenBy(i => Path.GetFileName(i))

View File

@@ -72,7 +72,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -60,8 +60,8 @@ namespace SabreTools.Library.DatFiles
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
Encoding enc = Utilities.GetEncoding(filename);
StreamReader sr = new StreamReader(Utilities.TryOpenRead(filename), enc);
while (!sr.EndOfStream)
{
@@ -122,7 +122,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -68,8 +68,8 @@ namespace SabreTools.Library.DatFiles
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
Encoding enc = Utilities.GetEncoding(filename);
StreamReader sr = new StreamReader(Utilities.TryOpenRead(filename), enc);
string gamename = "";
while (!sr.EndOfStream)
@@ -131,7 +131,7 @@ namespace SabreTools.Library.DatFiles
Disk disk = new Disk()
{
Name = romname,
SHA1 = Style.CleanListromHashData(split[0]),
SHA1 = Utilities.CleanListromHashData(split[0]),
MachineName = gamename,
};
@@ -145,7 +145,7 @@ namespace SabreTools.Library.DatFiles
Disk disk = new Disk()
{
Name = romname,
SHA1 = Style.CleanListromHashData(split[1]),
SHA1 = Utilities.CleanListromHashData(split[1]),
ItemStatus = ItemStatus.BadDump,
MachineName = gamename,
@@ -166,8 +166,8 @@ namespace SabreTools.Library.DatFiles
{
Name = romname,
Size = size,
CRC = Style.CleanListromHashData(split[1]),
SHA1 = Style.CleanListromHashData(split[2]),
CRC = Utilities.CleanListromHashData(split[1]),
SHA1 = Utilities.CleanListromHashData(split[2]),
MachineName = gamename,
};
@@ -201,8 +201,8 @@ namespace SabreTools.Library.DatFiles
{
Name = romname,
Size = size,
CRC = Style.CleanListromHashData(split[2]),
SHA1 = Style.CleanListromHashData(split[3]),
CRC = Utilities.CleanListromHashData(split[2]),
SHA1 = Utilities.CleanListromHashData(split[3]),
ItemStatus = ItemStatus.BadDump,
MachineName = gamename,
@@ -252,7 +252,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -69,8 +69,8 @@ namespace SabreTools.Library.DatFiles
ItemStatus its = ItemStatus.None;
List<string> parent = new List<string>();
Encoding enc = Style.GetEncoding(filename);
XmlReader xtr = FileTools.GetXmlTextReader(filename);
Encoding enc = Utilities.GetEncoding(filename);
XmlReader xtr = Utilities.GetXmlTextReader(filename);
// If we got a null reader, just return
if (xtr == null)
@@ -909,7 +909,7 @@ namespace SabreTools.Library.DatFiles
// If we're in clean mode, sanitize the game name
if (clean)
{
machine.Name = Style.CleanGameName(machine.Name.Split(Path.DirectorySeparatorChar));
machine.Name = Utilities.CleanGameName(machine.Name.Split(Path.DirectorySeparatorChar));
}
DatItem inrom;
@@ -1181,7 +1181,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -73,7 +73,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -74,7 +74,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -57,8 +57,8 @@ namespace SabreTools.Library.DatFiles
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
Encoding enc = Utilities.GetEncoding(filename);
StreamReader sr = new StreamReader(Utilities.TryOpenRead(filename), enc);
string blocktype = "";
while (!sr.EndOfStream)
@@ -208,7 +208,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -74,7 +74,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -58,8 +58,8 @@ namespace SabreTools.Library.DatFiles
bool remUnicode)
{
// Open a file reader
Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
Encoding enc = Utilities.GetEncoding(filename);
StreamReader sr = new StreamReader(Utilities.TryOpenRead(filename), enc);
// Create an empty list of columns to parse though
List<string> columns = new List<string>();
@@ -377,7 +377,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -76,7 +76,7 @@ namespace SabreTools.Library.DatFiles
try
{
Globals.Logger.User("Opening file for writing: {0}", outfile);
FileStream fs = FileTools.TryCreate(outfile);
FileStream fs = Utilities.TryCreate(outfile);
// If we get back null for some reason, just log and return
if (fs == null)

View File

@@ -1073,11 +1073,11 @@ namespace SabreTools.Library.DatItems
{
if ((x.Type == ItemType.Rom || x.Type == ItemType.Disk) && (y.Type == ItemType.Rom || y.Type == ItemType.Disk))
{
if (Path.GetDirectoryName(Style.RemovePathUnsafeCharacters(x.Name)) == Path.GetDirectoryName(Style.RemovePathUnsafeCharacters(y.Name)))
if (Path.GetDirectoryName(Utilities.RemovePathUnsafeCharacters(x.Name)) == Path.GetDirectoryName(Utilities.RemovePathUnsafeCharacters(y.Name)))
{
return nc.Compare(Path.GetFileName(Style.RemovePathUnsafeCharacters(x.Name)), Path.GetFileName(Style.RemovePathUnsafeCharacters(y.Name)));
return nc.Compare(Path.GetFileName(Utilities.RemovePathUnsafeCharacters(x.Name)), Path.GetFileName(Utilities.RemovePathUnsafeCharacters(y.Name)));
}
return nc.Compare(Path.GetDirectoryName(Style.RemovePathUnsafeCharacters(x.Name)), Path.GetDirectoryName(Style.RemovePathUnsafeCharacters(y.Name)));
return nc.Compare(Path.GetDirectoryName(Utilities.RemovePathUnsafeCharacters(x.Name)), Path.GetDirectoryName(Utilities.RemovePathUnsafeCharacters(y.Name)));
}
else if ((x.Type == ItemType.Rom || x.Type == ItemType.Disk) && (y.Type != ItemType.Rom && y.Type != ItemType.Disk))
{

View File

@@ -27,28 +27,28 @@ namespace SabreTools.Library.DatItems
// Disk information
public string MD5
{
get { return _md5.IsNullOrEmpty() ? null : Style.ByteArrayToString(_md5); }
set { _md5 = Style.StringToByteArray(value); }
get { return _md5.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_md5); }
set { _md5 = Utilities.StringToByteArray(value); }
}
public string SHA1
{
get { return _sha1.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha1); }
set { _sha1 = Style.StringToByteArray(value); }
get { return _sha1.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha1); }
set { _sha1 = Utilities.StringToByteArray(value); }
}
public string SHA256
{
get { return _sha256.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha256); }
set { _sha256 = Style.StringToByteArray(value); }
get { return _sha256.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha256); }
set { _sha256 = Utilities.StringToByteArray(value); }
}
public string SHA384
{
get { return _sha384.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha384); }
set { _sha384 = Style.StringToByteArray(value); }
get { return _sha384.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha384); }
set { _sha384 = Utilities.StringToByteArray(value); }
}
public string SHA512
{
get { return _sha512.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha512); }
set { _sha512 = Style.StringToByteArray(value); }
get { return _sha512.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha512); }
set { _sha512 = Utilities.StringToByteArray(value); }
}
public ItemStatus ItemStatus
{

View File

@@ -35,33 +35,33 @@ namespace SabreTools.Library.DatItems
}
public string CRC
{
get { return _crc.IsNullOrEmpty() ? null : Style.ByteArrayToString(_crc); }
set { _crc = Style.StringToByteArray(value); }
get { return _crc.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_crc); }
set { _crc = Utilities.StringToByteArray(value); }
}
public string MD5
{
get { return _md5.IsNullOrEmpty() ? null : Style.ByteArrayToString(_md5); }
set { _md5 = Style.StringToByteArray(value); }
get { return _md5.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_md5); }
set { _md5 = Utilities.StringToByteArray(value); }
}
public string SHA1
{
get { return _sha1.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha1); }
set { _sha1 = Style.StringToByteArray(value); }
get { return _sha1.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha1); }
set { _sha1 = Utilities.StringToByteArray(value); }
}
public string SHA256
{
get { return _sha256.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha256); }
set { _sha256 = Style.StringToByteArray(value); }
get { return _sha256.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha256); }
set { _sha256 = Utilities.StringToByteArray(value); }
}
public string SHA384
{
get { return _sha384.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha384); }
set { _sha384 = Style.StringToByteArray(value); }
get { return _sha384.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha384); }
set { _sha384 = Utilities.StringToByteArray(value); }
}
public string SHA512
{
get { return _sha512.IsNullOrEmpty() ? null : Style.ByteArrayToString(_sha512); }
set { _sha512 = Style.StringToByteArray(value); }
get { return _sha512.IsNullOrEmpty() ? null : Utilities.ByteArrayToString(_sha512); }
set { _sha512 = Utilities.StringToByteArray(value); }
}
public string Date
{

View File

@@ -77,12 +77,12 @@ namespace NaturalSort
{
if (!long.TryParse(left, out long x))
{
return Style.CompareNumeric(left, right);
return Utilities.CompareNumeric(left, right);
}
if (!long.TryParse(right, out long y))
{
return Style.CompareNumeric(left, right);
return Utilities.CompareNumeric(left, right);
}
// If we have an equal part, then make sure that "longer" ones are taken into account

View File

@@ -77,12 +77,12 @@ namespace NaturalSort
{
if (!long.TryParse(left, out long x))
{
return Style.CompareNumeric(right, left);
return Utilities.CompareNumeric(right, left);
}
if (!long.TryParse(right, out long y))
{
return Style.CompareNumeric(right, left);
return Utilities.CompareNumeric(right, left);
}
// If we have an equal part, then make sure that "longer" ones are taken into account

View File

@@ -426,7 +426,7 @@ namespace ROMVault2.SupportedFiles.Zip
}
// Now try to open the file for reading
_zipstream = FileTools.TryOpenRead(filename);
_zipstream = Utilities.TryOpenRead(filename);
int read = _zipstream.Read(new byte[1], 0, 1);
if (read != 1)
{
@@ -757,7 +757,7 @@ namespace ROMVault2.SupportedFiles.Zip
_zipstream.Dispose();
// Delete the failed file
FileTools.TryDeleteFile(_zipFileInfo.FullName);
Utilities.TryDeleteFile(_zipFileInfo.FullName);
_zipFileInfo = null;
_zipOpen = ZipOpenType.Closed;
}

View File

@@ -78,12 +78,12 @@ namespace ROMVault2.SupportedFiles.Zip
public string ExtraField
{
get { return Encoding.GetEncoding(858).GetString(_extraField); }
set { _extraField = Style.StringToByteArray(Style.ConvertAsciiToHex(value)); }
set { _extraField = Utilities.StringToByteArray(Utilities.ConvertAsciiToHex(value)); }
}
public string Comment
{
get { return Encoding.GetEncoding(858).GetString(_comment); }
set { _comment = Style.StringToByteArray(Style.ConvertAsciiToHex(value)); }
set { _comment = Utilities.StringToByteArray(Utilities.ConvertAsciiToHex(value)); }
}
public ulong RelativeOffset
{
@@ -333,7 +333,7 @@ namespace ROMVault2.SupportedFiles.Zip
// Now check for a unicode filename and set the flag accordingly
byte[] fileNameBytes;
if (Style.IsUnicode(_fileName))
if (Utilities.IsUnicode(_fileName))
{
_generalPurposeBitFlag |= GeneralPurposeBitFlag.LanguageEncodingFlag;
fileNameBytes = Encoding.UTF8.GetBytes(_fileName);
@@ -708,7 +708,7 @@ namespace ROMVault2.SupportedFiles.Zip
// Now check for a unicode filename and set the flag accordingly
byte[] fileNameBytes;
if (Style.IsUnicode(_fileName))
if (Utilities.IsUnicode(_fileName))
{
_generalPurposeBitFlag |= GeneralPurposeBitFlag.LanguageEncodingFlag;
fileNameBytes = Encoding.UTF8.GetBytes(_fileName);

View File

@@ -96,7 +96,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(outDir);
// Get all files from the input directory
List<string> files = FileTools.RetrieveFiles(_filename, new List<string>());
List<string> files = Utilities.RetrieveFiles(_filename, new List<string>());
// Now sort through to find the first file that matches
string match = files.Where(s => s.EndsWith(entryName)).FirstOrDefault();
@@ -135,7 +135,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(_filename);
// Get all files from the input directory
List<string> files = FileTools.RetrieveFiles(_filename, new List<string>());
List<string> files = Utilities.RetrieveFiles(_filename, new List<string>());
// Now sort through to find the first file that matches
string match = files.Where(s => s.EndsWith(entryName)).FirstOrDefault();
@@ -143,7 +143,7 @@ namespace SabreTools.Library.FileTypes
// If we had a file, copy that over to the new name
if (!String.IsNullOrEmpty(match))
{
FileTools.TryOpenRead(match).CopyTo(ms);
Utilities.TryOpenRead(match).CopyTo(ms);
realentry = match;
}
}
@@ -239,7 +239,7 @@ namespace SabreTools.Library.FileTypes
FileStream outputStream = null;
// Get the output folder name from the first rebuild rom
string fileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(rom.MachineName), Style.RemovePathUnsafeCharacters(rom.Name));
string fileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(rom.MachineName), Utilities.RemovePathUnsafeCharacters(rom.Name));
try
{
@@ -250,7 +250,7 @@ namespace SabreTools.Library.FileTypes
}
// Overwrite output files by default
outputStream = FileTools.TryCreate(fileName);
outputStream = Utilities.TryCreate(fileName);
// If the output stream isn't null
if (outputStream != null)

View File

@@ -70,8 +70,8 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(outDir);
// Decompress the _filename stream
FileStream outstream = FileTools.TryCreate(Path.Combine(outDir, Path.GetFileNameWithoutExtension(_filename)));
GZipStream gzstream = new GZipStream(FileTools.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress);
FileStream outstream = Utilities.TryCreate(Path.Combine(outDir, Path.GetFileNameWithoutExtension(_filename)));
GZipStream gzstream = new GZipStream(Utilities.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress);
gzstream.CopyTo(outstream);
// Dispose of the streams
@@ -117,7 +117,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(Path.GetDirectoryName(realEntry));
// Now open and write the file if possible
FileStream fs = FileTools.TryCreate(realEntry);
FileStream fs = Utilities.TryCreate(realEntry);
if (fs != null)
{
ms.Seek(0, SeekOrigin.Begin);
@@ -158,7 +158,7 @@ namespace SabreTools.Library.FileTypes
{
// Decompress the _filename stream
realEntry = Path.GetFileNameWithoutExtension(_filename);
GZipStream gzstream = new GZipStream(FileTools.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress);
GZipStream gzstream = new GZipStream(Utilities.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress);
// Write the file out
byte[] gbuffer = new byte[_bufferSize];
@@ -214,10 +214,10 @@ namespace SabreTools.Library.FileTypes
if (omitFromScan == Hash.SecureHashes)
{
Rom tempRom = new Rom(gamename, gamename, omitFromScan);
BinaryReader br = new BinaryReader(FileTools.TryOpenRead(_filename));
BinaryReader br = new BinaryReader(Utilities.TryOpenRead(_filename));
br.BaseStream.Seek(-8, SeekOrigin.End);
byte[] headercrc = br.ReadBytesReverse(4);
tempRom.CRC = Style.ByteArrayToString(headercrc);
tempRom.CRC = Utilities.ByteArrayToString(headercrc);
tempRom.Size = br.ReadInt32Reverse();
br.Dispose();
@@ -226,8 +226,8 @@ namespace SabreTools.Library.FileTypes
// Otherwise, use the stream directly
else
{
GZipStream gzstream = new GZipStream(FileTools.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress);
Rom gzipEntryRom = (Rom)FileTools.GetStreamInfo(gzstream, gzstream.Length, omitFromScan: omitFromScan);
GZipStream gzstream = new GZipStream(Utilities.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress);
Rom gzipEntryRom = (Rom)Utilities.GetStreamInfo(gzstream, gzstream.Length, omitFromScan: omitFromScan);
gzipEntryRom.Name = gzstream.FileName;
gzipEntryRom.MachineName = gamename;
gzipEntryRom.Date = (date && gzstream.LastModified != null ? gzstream.LastModified?.ToString("yyyy/MM/dd hh:mm:ss") : null);
@@ -286,7 +286,7 @@ namespace SabreTools.Library.FileTypes
// Check if the file is at least the minimum length
if (filesize < 40 /* bytes */)
{
Globals.Logger.Warning("Possibly corrupt file '{0}' with size {1}", Path.GetFullPath(_filename), Style.GetBytesReadable(filesize));
Globals.Logger.Warning("Possibly corrupt file '{0}' with size {1}", Path.GetFullPath(_filename), Utilities.GetBytesReadable(filesize));
return false;
}
@@ -295,7 +295,7 @@ namespace SabreTools.Library.FileTypes
byte[] headermd5; // MD5
byte[] headercrc; // CRC
ulong headersz; // Int64 size
BinaryReader br = new BinaryReader(FileTools.TryOpenRead(_filename));
BinaryReader br = new BinaryReader(Utilities.TryOpenRead(_filename));
header = br.ReadBytes(12);
headermd5 = br.ReadBytes(16);
headercrc = br.ReadBytes(4);
@@ -353,7 +353,7 @@ namespace SabreTools.Library.FileTypes
// Check if the file is at least the minimum length
if (filesize < 40 /* bytes */)
{
Globals.Logger.Warning("Possibly corrupt file '{0}' with size {1}", Path.GetFullPath(_filename), Style.GetBytesReadable(filesize));
Globals.Logger.Warning("Possibly corrupt file '{0}' with size {1}", Path.GetFullPath(_filename), Utilities.GetBytesReadable(filesize));
return null;
}
@@ -362,7 +362,7 @@ namespace SabreTools.Library.FileTypes
byte[] headermd5; // MD5
byte[] headercrc; // CRC
ulong headersz; // Int64 size
BinaryReader br = new BinaryReader(FileTools.TryOpenRead(_filename));
BinaryReader br = new BinaryReader(Utilities.TryOpenRead(_filename));
header = br.ReadBytes(12);
headermd5 = br.ReadBytes(16);
headercrc = br.ReadBytes(4);
@@ -386,8 +386,8 @@ namespace SabreTools.Library.FileTypes
}
// Now convert the data and get the right position
string gzmd5 = Style.ByteArrayToString(headermd5);
string gzcrc = Style.ByteArrayToString(headercrc);
string gzmd5 = Utilities.ByteArrayToString(headermd5);
string gzcrc = Utilities.ByteArrayToString(headercrc);
long extractedsize = (long)headersz;
Rom rom = new Rom
@@ -430,7 +430,7 @@ namespace SabreTools.Library.FileTypes
inputFile = Path.GetFullPath(inputFile);
// Get the file stream for the file and write out
return Write(FileTools.TryOpenRead(inputFile), outDir, rom, date, romba);
return Write(Utilities.TryOpenRead(inputFile), outDir, rom, date, romba);
}
/// <summary>
@@ -461,7 +461,7 @@ namespace SabreTools.Library.FileTypes
outDir = Path.GetFullPath(outDir);
// Now get the Rom info for the file so we have hashes and size
rom = (Rom)FileTools.GetStreamInfo(inputStream, inputStream.Length, keepReadOpen: true);
rom = (Rom)Utilities.GetStreamInfo(inputStream, inputStream.Length, keepReadOpen: true);
// Get the output file name
string outfile = null;
@@ -469,7 +469,7 @@ namespace SabreTools.Library.FileTypes
// If we have a romba output, add the romba path
if (romba)
{
outfile = Path.Combine(outDir, Style.GetRombaPath(rom.SHA1)); // TODO: When updating to SHA-256, this needs to update to SHA256
outfile = Path.Combine(outDir, Utilities.GetRombaPath(rom.SHA1)); // TODO: When updating to SHA-256, this needs to update to SHA256
// Check to see if the folder needs to be created
if (!Directory.Exists(Path.GetDirectoryName(outfile)))
@@ -487,15 +487,15 @@ namespace SabreTools.Library.FileTypes
if (!File.Exists(outfile))
{
// Compress the input stream
FileStream outputStream = FileTools.TryCreate(outfile);
FileStream outputStream = Utilities.TryCreate(outfile);
// Open the output file for writing
BinaryWriter sw = new BinaryWriter(outputStream);
// Write standard header and TGZ info
byte[] data = Constants.TorrentGZHeader
.Concat(Style.StringToByteArray(rom.MD5)) // MD5
.Concat(Style.StringToByteArray(rom.CRC)) // CRC
.Concat(Utilities.StringToByteArray(rom.MD5)) // MD5
.Concat(Utilities.StringToByteArray(rom.CRC)) // CRC
.ToArray();
sw.Write(data);
sw.Write((ulong)rom.Size); // Long size (Unsigned, Mirrored)
@@ -514,7 +514,7 @@ namespace SabreTools.Library.FileTypes
ds.Dispose();
// Now write the standard footer
sw.Write(Style.StringToByteArray(rom.CRC).Reverse().ToArray());
sw.Write(Utilities.StringToByteArray(rom.CRC).Reverse().ToArray());
sw.Write((uint)rom.Size);
// Dispose of everything

View File

@@ -115,7 +115,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(Path.GetDirectoryName(realEntry));
// Now open and write the file if possible
FileStream fs = FileTools.TryCreate(realEntry);
FileStream fs = Utilities.TryCreate(realEntry);
if (fs != null)
{
ms.Seek(0, SeekOrigin.Begin);
@@ -194,7 +194,7 @@ namespace SabreTools.Library.FileTypes
try
{
SharpCompress.Archives.Rar.RarArchive ra = SharpCompress.Archives.Rar.RarArchive.Open(FileTools.TryOpenRead(_filename));
SharpCompress.Archives.Rar.RarArchive ra = SharpCompress.Archives.Rar.RarArchive.Open(Utilities.TryOpenRead(_filename));
foreach (RarArchiveEntry entry in ra.Entries.Where(e => e != null && !e.IsDirectory))
{
// If secure hashes are disabled, do a quickscan
@@ -215,7 +215,7 @@ namespace SabreTools.Library.FileTypes
else
{
Stream entryStream = entry.OpenEntryStream();
Rom rarEntryRom = (Rom)FileTools.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan);
Rom rarEntryRom = (Rom)Utilities.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan);
rarEntryRom.Name = entry.Key;
rarEntryRom.MachineName = gamename;
rarEntryRom.Date = entry.LastModifiedTime?.ToString("yyyy/MM/dd hh:mm:ss");
@@ -247,7 +247,7 @@ namespace SabreTools.Library.FileTypes
return;
}
BinaryReader br = new BinaryReader(FileTools.TryOpenRead(_filename));
BinaryReader br = new BinaryReader(Utilities.TryOpenRead(_filename));
// Check for the signature first (Skipping the SFX Module)
byte[] signature = br.ReadBytes(8);
@@ -517,7 +517,7 @@ namespace SabreTools.Library.FileTypes
public override bool Write(string inputFile, string outDir, Rom rom, bool date = false, bool romba = false)
{
// Get the file stream for the file and write out
return Write(FileTools.TryOpenRead(inputFile), outDir, rom, date, romba);
return Write(Utilities.TryOpenRead(inputFile), outDir, rom, date, romba);
}
/// <summary>

View File

@@ -73,7 +73,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(outDir);
// Extract all files to the temp directory
SharpCompress.Archives.SevenZip.SevenZipArchive sza = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(FileTools.TryOpenRead(_filename));
SharpCompress.Archives.SevenZip.SevenZipArchive sza = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(Utilities.TryOpenRead(_filename));
foreach (SevenZipArchiveEntry entry in sza.Entries)
{
entry.WriteToDirectory(outDir, new ExtractionOptions { PreserveFileTime = true, ExtractFullPath = true, Overwrite = true });
@@ -118,7 +118,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(Path.GetDirectoryName(realEntry));
// Now open and write the file if possible
FileStream fs = FileTools.TryCreate(realEntry);
FileStream fs = Utilities.TryCreate(realEntry);
if (fs != null)
{
ms.Seek(0, SeekOrigin.Begin);
@@ -198,7 +198,7 @@ namespace SabreTools.Library.FileTypes
try
{
SharpCompress.Archives.SevenZip.SevenZipArchive sza = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(FileTools.TryOpenRead(_filename));
SharpCompress.Archives.SevenZip.SevenZipArchive sza = SharpCompress.Archives.SevenZip.SevenZipArchive.Open(Utilities.TryOpenRead(_filename));
foreach (SevenZipArchiveEntry entry in sza.Entries.Where(e => e != null && !e.IsDirectory))
{
// If secure hashes are disabled, do a quickscan
@@ -219,7 +219,7 @@ namespace SabreTools.Library.FileTypes
else
{
Stream entryStream = entry.OpenEntryStream();
Rom sevenZipEntryRom = (Rom)FileTools.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan);
Rom sevenZipEntryRom = (Rom)Utilities.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan);
sevenZipEntryRom.Name = entry.Key;
sevenZipEntryRom.MachineName = gamename;
sevenZipEntryRom.Date = (date && entry.LastModifiedTime != null ? entry.LastModifiedTime?.ToString("yyyy/MM/dd hh:mm:ss") : null);
@@ -292,7 +292,7 @@ namespace SabreTools.Library.FileTypes
{
try
{
Stream fread = FileTools.TryOpenRead(_filename);
Stream fread = Utilities.TryOpenRead(_filename);
uint ar, offs = 0;
fread.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[128];
@@ -338,7 +338,7 @@ namespace SabreTools.Library.FileTypes
public override bool Write(string inputFile, string outDir, Rom rom, bool date = false, bool romba = false)
{
// Get the file stream for the file and write out
return Write(FileTools.TryOpenRead(inputFile), outDir, rom, date: date);
return Write(Utilities.TryOpenRead(inputFile), outDir, rom, date: date);
}
/// <summary>
@@ -371,7 +371,7 @@ namespace SabreTools.Library.FileTypes
inputStream.Seek(0, SeekOrigin.Begin);
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".7z") ? "" : ".7z"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".7z") ? "" : ".7z"));
// Set internal variables
SevenZipBase.SetLibraryPath("7za.dll");
@@ -503,19 +503,19 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);
// Now make the file T7Z
// TODO: Add ACTUAL T7Z compatible code
BinaryWriter bw = new BinaryWriter(FileTools.TryOpenReadWrite(archiveFileName));
BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));
bw.Seek(0, SeekOrigin.Begin);
bw.Write(Constants.Torrent7ZipHeader);
bw.Seek(0, SeekOrigin.End);
using (oldZipFile = new SevenZipExtractor(FileTools.TryOpenReadWrite(archiveFileName)))
using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
{
// Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
@@ -573,7 +573,7 @@ namespace SabreTools.Library.FileTypes
}
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".7z") ? "" : ".7z"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".7z") ? "" : ".7z"));
// Set internal variables
SevenZipBase.SetLibraryPath("7za.dll");
@@ -628,8 +628,8 @@ namespace SabreTools.Library.FileTypes
zipFile.CompressionMode = CompressionMode.Append;
}
FileTools.CleanDirectory(tempPath);
FileTools.TryDeleteDirectory(tempPath);
Utilities.CleanDirectory(tempPath);
Utilities.TryDeleteDirectory(tempPath);
}
// Otherwise, sort the input files and write out in the correct order
@@ -684,7 +684,7 @@ namespace SabreTools.Library.FileTypes
// If we have the input file, add it now
if (index < 0)
{
FileStream inputStream = FileTools.TryOpenRead(inputFiles[-index - 1]);
FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]);
// Create a stream dictionary
Dictionary<string, Stream> dict = new Dictionary<string, Stream>();
@@ -727,19 +727,19 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);
// Now make the file T7Z
// TODO: Add ACTUAL T7Z compatible code
BinaryWriter bw = new BinaryWriter(FileTools.TryOpenReadWrite(archiveFileName));
BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));
bw.Seek(0, SeekOrigin.Begin);
bw.Write(Constants.Torrent7ZipHeader);
bw.Seek(0, SeekOrigin.End);
using (oldZipFile = new SevenZipExtractor(FileTools.TryOpenReadWrite(archiveFileName)))
using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
{
// Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
byte[] tempsig = Constants.Torrent7ZipSignature;

View File

@@ -117,7 +117,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(Path.GetDirectoryName(realEntry));
// Now open and write the file if possible
FileStream fs = FileTools.TryCreate(realEntry);
FileStream fs = Utilities.TryCreate(realEntry);
if (fs != null)
{
ms.Seek(0, SeekOrigin.Begin);
@@ -196,7 +196,7 @@ namespace SabreTools.Library.FileTypes
try
{
TarArchive ta = TarArchive.Open(FileTools.TryOpenRead(_filename));
TarArchive ta = TarArchive.Open(Utilities.TryOpenRead(_filename));
foreach (TarArchiveEntry entry in ta.Entries.Where(e => e != null && !e.IsDirectory))
{
// If secure hashes are disabled, do a quickscan
@@ -217,7 +217,7 @@ namespace SabreTools.Library.FileTypes
else
{
Stream entryStream = entry.OpenEntryStream();
Rom tarEntryRom = (Rom)FileTools.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan);
Rom tarEntryRom = (Rom)Utilities.GetStreamInfo(entryStream, entry.Size, omitFromScan: omitFromScan);
tarEntryRom.Name = entry.Key;
tarEntryRom.MachineName = gamename;
tarEntryRom.Date = entry.LastModifiedTime?.ToString("yyyy/MM/dd hh:mm:ss");
@@ -302,7 +302,7 @@ namespace SabreTools.Library.FileTypes
public override bool Write(string inputFile, string outDir, Rom rom, bool date = false, bool romba = false)
{
// Get the file stream for the file and write out
return Write(FileTools.TryOpenRead(inputFile), outDir, rom, date: date);
return Write(Utilities.TryOpenRead(inputFile), outDir, rom, date: date);
}
/// <summary>
@@ -332,7 +332,7 @@ namespace SabreTools.Library.FileTypes
}
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".tar") ? "" : ".tar"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".tar") ? "" : ".tar"));
// Set internal variables
TarArchive oldTarFile = TarArchive.Create();
@@ -451,7 +451,7 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);
@@ -494,7 +494,7 @@ namespace SabreTools.Library.FileTypes
}
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".tar") ? "" : ".tar"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".tar") ? "" : ".tar"));
// Set internal variables
TarArchive oldTarFile = TarArchive.Create();
@@ -536,7 +536,7 @@ namespace SabreTools.Library.FileTypes
}
// Copy the input stream to the output
tarFile.AddEntry(roms[index].Name, FileTools.TryOpenRead(inputFiles[index]), size: roms[index].Size, modified: usableDate);
tarFile.AddEntry(roms[index].Name, Utilities.TryOpenRead(inputFiles[index]), size: roms[index].Size, modified: usableDate);
}
}
@@ -596,7 +596,7 @@ namespace SabreTools.Library.FileTypes
}
// Copy the input file to the output
tarFile.AddEntry(roms[-index - 1].Name, FileTools.TryOpenRead(inputFiles[-index - 1]), size: roms[-index - 1].Size, modified: usableDate);
tarFile.AddEntry(roms[-index - 1].Name, Utilities.TryOpenRead(inputFiles[-index - 1]), size: roms[-index - 1].Size, modified: usableDate);
}
// Otherwise, copy the file from the old archive
@@ -632,7 +632,7 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);

View File

@@ -94,7 +94,7 @@ namespace SabreTools.Library.FileTypes
continue;
}
FileStream writeStream = FileTools.TryCreate(Path.Combine(outDir, zf.Entries[i].FileName));
FileStream writeStream = Utilities.TryCreate(Path.Combine(outDir, zf.Entries[i].FileName));
// If the stream is smaller than the buffer, just run one loop through to avoid issues
if (streamsize < _bufferSize)
@@ -160,7 +160,7 @@ namespace SabreTools.Library.FileTypes
Directory.CreateDirectory(Path.GetDirectoryName(realEntry));
// Now open and write the file if possible
FileStream fs = FileTools.TryCreate(realEntry);
FileStream fs = Utilities.TryCreate(realEntry);
if (fs != null)
{
ms.Seek(0, SeekOrigin.Begin);
@@ -300,7 +300,7 @@ namespace SabreTools.Library.FileTypes
string newname = zf.Entries[i].FileName;
long newsize = (long)zf.Entries[i].UncompressedSize;
string newcrc = BitConverter.ToString(zf.Entries[i].CRC.Reverse().ToArray(), 0, zf.Entries[i].CRC.Length).Replace("-", string.Empty).ToLowerInvariant();
string convertedDate = Style.ConvertMsDosTimeFormatToDateTime(zf.Entries[i].LastMod).ToString("yyyy/MM/dd hh:mm:ss");
string convertedDate = Utilities.ConvertMsDosTimeFormatToDateTime(zf.Entries[i].LastMod).ToString("yyyy/MM/dd hh:mm:ss");
found.Add(new Rom
{
@@ -316,10 +316,10 @@ namespace SabreTools.Library.FileTypes
// Otherwise, use the stream directly
else
{
Rom zipEntryRom = (Rom)FileTools.GetStreamInfo(readStream, (long)zf.Entries[i].UncompressedSize, omitFromScan: omitFromScan);
Rom zipEntryRom = (Rom)Utilities.GetStreamInfo(readStream, (long)zf.Entries[i].UncompressedSize, omitFromScan: omitFromScan);
zipEntryRom.Name = zf.Entries[i].FileName;
zipEntryRom.MachineName = gamename;
string convertedDate = Style.ConvertMsDosTimeFormatToDateTime(zf.Entries[i].LastMod).ToString("yyyy/MM/dd hh:mm:ss");
string convertedDate = Utilities.ConvertMsDosTimeFormatToDateTime(zf.Entries[i].LastMod).ToString("yyyy/MM/dd hh:mm:ss");
zipEntryRom.Date = (date ? convertedDate : null);
found.Add(zipEntryRom);
zr = zf.CloseReadStream();
@@ -406,7 +406,7 @@ namespace SabreTools.Library.FileTypes
public override bool Write(string inputFile, string outDir, Rom rom, bool date = false, bool romba = false)
{
// Get the file stream for the file and write out
return Write(FileTools.TryOpenRead(inputFile), outDir, rom, date: date);
return Write(Utilities.TryOpenRead(inputFile), outDir, rom, date: date);
}
/// <summary>
@@ -439,7 +439,7 @@ namespace SabreTools.Library.FileTypes
inputStream.Seek(0, SeekOrigin.Begin);
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".zip") ? "" : ".zip"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".zip") ? "" : ".zip"));
// Set internal variables
Stream writeStream = null;
@@ -467,7 +467,7 @@ namespace SabreTools.Library.FileTypes
DateTime dt = DateTime.Now;
if (date && !String.IsNullOrEmpty(rom.Date) && DateTime.TryParse(rom.Date.Replace('\\', '/'), out dt))
{
uint msDosDateTime = Style.ConvertDateTimeToMsDosTimeFormat(dt);
uint msDosDateTime = Utilities.ConvertDateTimeToMsDosTimeFormat(dt);
zipFile.OpenWriteStream(false, false, rom.Name.Replace('\\', '/'), istreamSize,
SabreTools.Library.Data.CompressionMethod.Deflated, out writeStream, lastMod: msDosDateTime);
}
@@ -538,7 +538,7 @@ namespace SabreTools.Library.FileTypes
DateTime dt = DateTime.Now;
if (date && !String.IsNullOrEmpty(rom.Date) && DateTime.TryParse(rom.Date.Replace('\\', '/'), out dt))
{
uint msDosDateTime = Style.ConvertDateTimeToMsDosTimeFormat(dt);
uint msDosDateTime = Utilities.ConvertDateTimeToMsDosTimeFormat(dt);
zipFile.OpenWriteStream(false, false, rom.Name.Replace('\\', '/'), istreamSize,
SabreTools.Library.Data.CompressionMethod.Deflated, out writeStream, lastMod: msDosDateTime);
}
@@ -600,7 +600,7 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);
@@ -643,7 +643,7 @@ namespace SabreTools.Library.FileTypes
}
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".zip") ? "" : ".zip"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".zip") ? "" : ".zip"));
// Set internal variables
Stream writeStream = null;
@@ -682,13 +682,13 @@ namespace SabreTools.Library.FileTypes
int index = inputIndexMap[key];
// Open the input file for reading
Stream freadStream = FileTools.TryOpenRead(inputFiles[index]);
Stream freadStream = Utilities.TryOpenRead(inputFiles[index]);
ulong istreamSize = (ulong)(new FileInfo(inputFiles[index]).Length);
DateTime dt = DateTime.Now;
if (date && !String.IsNullOrEmpty(roms[index].Date) && DateTime.TryParse(roms[index].Date.Replace('\\', '/'), out dt))
{
uint msDosDateTime = Style.ConvertDateTimeToMsDosTimeFormat(dt);
uint msDosDateTime = Utilities.ConvertDateTimeToMsDosTimeFormat(dt);
zipFile.OpenWriteStream(false, false, roms[index].Name.Replace('\\', '/'), istreamSize,
SabreTools.Library.Data.CompressionMethod.Deflated, out writeStream, lastMod: msDosDateTime);
}
@@ -759,13 +759,13 @@ namespace SabreTools.Library.FileTypes
if (index < 0)
{
// Open the input file for reading
Stream freadStream = FileTools.TryOpenRead(inputFiles[-index - 1]);
Stream freadStream = Utilities.TryOpenRead(inputFiles[-index - 1]);
ulong istreamSize = (ulong)(new FileInfo(inputFiles[-index - 1]).Length);
DateTime dt = DateTime.Now;
if (date && !String.IsNullOrEmpty(roms[-index - 1].Date) && DateTime.TryParse(roms[-index - 1].Date.Replace('\\', '/'), out dt))
{
uint msDosDateTime = Style.ConvertDateTimeToMsDosTimeFormat(dt);
uint msDosDateTime = Utilities.ConvertDateTimeToMsDosTimeFormat(dt);
zipFile.OpenWriteStream(false, false, roms[-index - 1].Name.Replace('\\', '/'), istreamSize,
SabreTools.Library.Data.CompressionMethod.Deflated, out writeStream, lastMod: msDosDateTime);
}
@@ -826,7 +826,7 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);

View File

@@ -136,7 +136,7 @@ namespace SabreTools.Library.FileTypes
public override bool Write(string inputFile, string outDir, Rom rom, bool date = false, bool romba = false)
{
// Get the file stream for the file and write out
return Write(FileTools.TryOpenRead(inputFile), outDir, rom, date: date);
return Write(Utilities.TryOpenRead(inputFile), outDir, rom, date: date);
}
/// <summary>
@@ -169,7 +169,7 @@ namespace SabreTools.Library.FileTypes
inputStream.Seek(0, SeekOrigin.Begin);
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".xz") ? "" : ".xz"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(rom.MachineName) + (rom.MachineName.EndsWith(".xz") ? "" : ".xz"));
// Set internal variables
SevenZipBase.SetLibraryPath("7za.dll");
@@ -301,19 +301,19 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);
// Now make the file T7Z
// TODO: Add ACTUAL T7Z compatible code
BinaryWriter bw = new BinaryWriter(FileTools.TryOpenReadWrite(archiveFileName));
BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));
bw.Seek(0, SeekOrigin.Begin);
bw.Write(Constants.Torrent7ZipHeader);
bw.Seek(0, SeekOrigin.End);
using (oldZipFile = new SevenZipExtractor(FileTools.TryOpenReadWrite(archiveFileName)))
using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
{
// Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
@@ -371,7 +371,7 @@ namespace SabreTools.Library.FileTypes
}
// Get the output archive name from the first rebuild rom
string archiveFileName = Path.Combine(outDir, Style.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".xz") ? "" : ".xz"));
string archiveFileName = Path.Combine(outDir, Utilities.RemovePathUnsafeCharacters(roms[0].MachineName) + (roms[0].MachineName.EndsWith(".xz") ? "" : ".xz"));
// Set internal variables
SevenZipBase.SetLibraryPath("7za.dll");
@@ -426,8 +426,8 @@ namespace SabreTools.Library.FileTypes
zipFile.CompressionMode = CompressionMode.Append;
}
FileTools.CleanDirectory(tempPath);
FileTools.TryDeleteDirectory(tempPath);
Utilities.CleanDirectory(tempPath);
Utilities.TryDeleteDirectory(tempPath);
}
// Otherwise, sort the input files and write out in the correct order
@@ -482,7 +482,7 @@ namespace SabreTools.Library.FileTypes
// If we have the input file, add it now
if (index < 0)
{
FileStream inputStream = FileTools.TryOpenRead(inputFiles[-index - 1]);
FileStream inputStream = Utilities.TryOpenRead(inputFiles[-index - 1]);
// Create a stream dictionary
Dictionary<string, Stream> dict = new Dictionary<string, Stream>();
@@ -525,19 +525,19 @@ namespace SabreTools.Library.FileTypes
// If the old file exists, delete it and replace
if (File.Exists(archiveFileName))
{
FileTools.TryDeleteFile(archiveFileName);
Utilities.TryDeleteFile(archiveFileName);
}
File.Move(tempFile, archiveFileName);
// Now make the file T7Z
// TODO: Add ACTUAL T7Z compatible code
BinaryWriter bw = new BinaryWriter(FileTools.TryOpenReadWrite(archiveFileName));
BinaryWriter bw = new BinaryWriter(Utilities.TryOpenReadWrite(archiveFileName));
bw.Seek(0, SeekOrigin.Begin);
bw.Write(Constants.Torrent7ZipHeader);
bw.Seek(0, SeekOrigin.End);
using (oldZipFile = new SevenZipExtractor(FileTools.TryOpenReadWrite(archiveFileName)))
using (oldZipFile = new SevenZipExtractor(Utilities.TryOpenReadWrite(archiveFileName)))
{
// Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
byte[] tempsig = Constants.Torrent7ZipSignature;

View File

@@ -34,7 +34,7 @@ namespace SabreTools.Library.Reports
public BaseReport(DatFile datfile, string filename, bool baddumpCol = false, bool nodumpCol = false)
{
_datFile = datfile;
_writer = new StreamWriter(FileTools.TryCreate(filename));
_writer = new StreamWriter(Utilities.TryCreate(filename));
_baddumpCol = baddumpCol;
_nodumpCol = nodumpCol;
}

View File

@@ -54,7 +54,7 @@ namespace SabreTools.Library.Reports
string line = "\t\t\t<tr" + (_datFile.FileName.StartsWith("DIR: ")
? " class=\"dir\"><td>" + HttpUtility.HtmlEncode(_datFile.FileName.Remove(0, 5))
: "><td>" + HttpUtility.HtmlEncode(_datFile.FileName)) + "</td>"
+ "<td align=\"right\">" + Style.GetBytesReadable(_datFile.TotalSize) + "</td>"
+ "<td align=\"right\">" + Utilities.GetBytesReadable(_datFile.TotalSize) + "</td>"
+ "<td align=\"right\">" + (game == -1 ? _datFile.Keys.Count() : game) + "</td>"
+ "<td align=\"right\">" + _datFile.RomCount + "</td>"
+ "<td align=\"right\">" + _datFile.DiskCount + "</td>"

View File

@@ -50,7 +50,7 @@ namespace SabreTools.Library.Reports
{
string line = @"'" + _datFile.FileName + @"':
--------------------------------------------------
Uncompressed size: " + Style.GetBytesReadable(_datFile.TotalSize) + @"
Uncompressed size: " + Utilities.GetBytesReadable(_datFile.TotalSize) + @"
Games found: " + (game == -1 ? _datFile.Keys.Count() : game) + @"
Roms found: " + _datFile.RomCount + @"
Disks found: " + _datFile.DiskCount + @"

View File

@@ -182,12 +182,11 @@
<Compile Include="Skippers\Skipper.cs" />
<Compile Include="Skippers\SkipperRule.cs" />
<Compile Include="Tools\InternalStopwatch.cs" />
<Compile Include="Tools\FileTools.cs" />
<Compile Include="Tools\Utilities.cs" />
<Compile Include="Tools\DatabaseTools.cs" />
<Compile Include="Data\Enums.cs" />
<Compile Include="Tools\Logger.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Tools\Style.cs" />
<Compile Include="Data\Build.cs" />
</ItemGroup>
<ItemGroup>

View File

@@ -72,7 +72,7 @@ namespace SabreTools.Library.Skippers
SourceFile = Path.GetFileNameWithoutExtension(filename);
Logger logger = new Logger();
XmlReader xtr = FileTools.GetXmlTextReader(filename);
XmlReader xtr = Utilities.GetXmlTextReader(filename);
if (xtr == null)
{
@@ -347,7 +347,7 @@ namespace SabreTools.Library.Skippers
return new SkipperRule();
}
return GetMatchingRule(FileTools.TryOpenRead(input), skipperName);
return GetMatchingRule(Utilities.TryOpenRead(input), skipperName);
}
/// <summary>

View File

@@ -50,12 +50,12 @@ namespace SabreTools.Library.Skippers
}
Globals.Logger.User("Attempting to apply rule to '{0}'", input);
success = TransformStream(FileTools.TryOpenRead(input), FileTools.TryCreate(output));
success = TransformStream(Utilities.TryOpenRead(input), Utilities.TryCreate(output));
// If the output file has size 0, delete it
if (new FileInfo(output).Length == 0)
{
FileTools.TryDeleteFile(output);
Utilities.TryDeleteFile(output);
success = false;
}

View File

@@ -86,7 +86,7 @@ namespace SabreTools.Library.Tools
try
{
FileStream logfile = FileTools.TryCreate(Path.Combine(_basepath, _filename));
FileStream logfile = Utilities.TryCreate(Path.Combine(_basepath, _filename));
_log = new StreamWriter(logfile, Encoding.UTF8, (int)(4 * Constants.KibiByte), true);
_log.AutoFlush = true;

View File

@@ -1,774 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using SabreTools.Library.Data;
#if MONO
using System.IO;
#else
using Alphaleonis.Win32.Filesystem;
using FileStream = System.IO.FileStream;
#endif
namespace SabreTools.Library.Tools
{
/// <summary>
/// Include character normalization and replacement mappings
/// </summary>
public static class Style
{
#region DAT Cleaning
/// <summary>
/// Clean a game (or rom) name to the WoD standard
/// </summary>
/// <param name="game">Name of the game to be cleaned</param>
/// <returns>The cleaned name</returns>
public static string CleanGameName(string game)
{
///Run the name through the filters to make sure that it's correct
game = NormalizeChars(game);
game = RussianToLatin(game);
game = SearchPattern(game);
game = new Regex(@"(([[(].*[\)\]] )?([^([]+))").Match(game).Groups[1].Value;
game = game.TrimStart().TrimEnd();
return game;
}
/// <summary>
/// Clean a game (or rom) name to the WoD standard
/// </summary>
/// <param name="game">Array representing the path to be cleaned</param>
/// <returns>The cleaned name</returns>
public static string CleanGameName(string[] game)
{
game[game.Length - 1] = CleanGameName(game[game.Length - 1]);
string outgame = String.Join(Path.DirectorySeparatorChar.ToString(), game);
outgame = outgame.TrimStart().TrimEnd();
return outgame;
}
/// <summary>
/// Clean a hash string and pad to the correct size
/// </summary>
/// <param name="hash">Hash string to sanitize</param>
/// <param name="padding">Amount of characters to pad to</param>
/// <returns>Cleaned string</returns>
public static string CleanHashData(string hash, int padding)
{
// If we have a known blank hash, return blank
if (string.IsNullOrEmpty(hash) || hash == "-" || hash == "_")
{
return "";
}
// Check to see if it's a "hex" hash
hash = hash.Trim().Replace("0x", "");
// If we have a blank hash now, return blank
if (string.IsNullOrEmpty(hash))
{
return "";
}
// If the hash shorter than the required length, pad it
if (hash.Length < padding)
{
hash = hash.PadLeft(padding, '0');
}
// If the hash is longer than the required length, it's invalid
else if (hash.Length > padding)
{
return "";
}
// Now normalize the hash
hash = hash.ToLowerInvariant();
// Otherwise, make sure that every character is a proper match
for (int i = 0; i < hash.Length; i++)
{
if ((hash[i] < '0' || hash[i] > '9') && (hash[i] < 'a' || hash[i] > 'f'))
{
hash = "";
break;
}
}
return hash;
}
/// <summary>
/// Clean a hash string from a Listrom DAT
/// </summary>
/// <param name="hash">Hash string to sanitize</param>
/// <returns>Cleaned string</returns>
public static string CleanListromHashData(string hash)
{
if (hash.StartsWith("CRC"))
{
return hash.Substring(4, 8).ToLowerInvariant();
}
else if (hash.StartsWith("SHA1"))
{
return hash.Substring(5, 40).ToLowerInvariant();
}
return hash;
}
/// <summary>
/// Replace accented characters
/// </summary>
/// <param name="input">String to be parsed</param>
/// <returns>String with characters replaced</returns>
public static string NormalizeChars(string input)
{
string[,] charmap = {
{ "Á", "A" }, { "á", "a" },
{ "À", "A" }, { "à", "a" },
{ "Â", "A" }, { "â", "a" },
{ "Ä", "Ae" }, { "ä", "ae" },
{ "Ã", "A" }, { "ã", "a" },
{ "Å", "A" }, { "å", "a" },
{ "Æ", "Ae" }, { "æ", "ae" },
{ "Ç", "C" }, { "ç", "c" },
{ "Ð", "D" }, { "ð", "d" },
{ "É", "E" }, { "é", "e" },
{ "È", "E" }, { "è", "e" },
{ "Ê", "E" }, { "ê", "e" },
{ "Ë", "E" }, { "ë", "e" },
{ "ƒ", "f" },
{ "Í", "I" }, { "í", "i" },
{ "Ì", "I" }, { "ì", "i" },
{ "Î", "I" }, { "î", "i" },
{ "Ï", "I" }, { "ï", "i" },
{ "Ñ", "N" }, { "ñ", "n" },
{ "Ó", "O" }, { "ó", "o" },
{ "Ò", "O" }, { "ò", "o" },
{ "Ô", "O" }, { "ô", "o" },
{ "Ö", "Oe" }, { "ö", "oe" },
{ "Õ", "O" }, { "õ", "o" },
{ "Ø", "O" }, { "ø", "o" },
{ "Š", "S" }, { "š", "s" },
{ "ß", "ss" },
{ "Þ", "B" }, { "þ", "b" },
{ "Ú", "U" }, { "ú", "u" },
{ "Ù", "U" }, { "ù", "u" },
{ "Û", "U" }, { "û", "u" },
{ "Ü", "Ue" }, { "ü", "ue" },
{ "ÿ", "y" },
{ "Ý", "Y" }, { "ý", "y" },
{ "Ž", "Z" }, { "ž", "z" },
};
for (int i = 0; i < charmap.GetLength(0); i++)
{
input = input.Replace(charmap[i, 0], charmap[i, 1]);
}
return input;
}
/// <summary>
/// Convert Cyrillic lettering to Latin lettering
/// </summary>
/// <param name="input">String to be parsed</param>
/// <returns>String with characters replaced</returns>
public static string RussianToLatin(string input)
{
string[,] charmap = {
{ "А", "A" }, { "Б", "B" }, { "В", "V" }, { "Г", "G" }, { "Д", "D" },
{ "Е", "E" }, { "Ё", "Yo" }, { "Ж", "Zh" }, { "З", "Z" }, { "И", "I" },
{ "Й", "J" }, { "К", "K" }, { "Л", "L" }, { "М", "M" }, { "Н", "N" },
{ "О", "O" }, { "П", "P" }, { "Р", "R" }, { "С", "S" }, { "Т", "T" },
{ "У", "U" }, { "Ф", "f" }, { "Х", "Kh" }, { "Ц", "Ts" }, { "Ч", "Ch" },
{ "Ш", "Sh" }, { "Щ", "Sch" }, { "Ъ", "" }, { "Ы", "y" }, { "Ь", "" },
{ "Э", "e" }, { "Ю", "yu" }, { "Я", "ya" }, { "а", "a" }, { "б", "b" },
{ "в", "v" }, { "г", "g" }, { "д", "d" }, { "е", "e" }, { "ё", "yo" },
{ "ж", "zh" }, { "з", "z" }, { "и", "i" }, { "й", "j" }, { "к", "k" },
{ "л", "l" }, { "м", "m" }, { "н", "n" }, { "о", "o" }, { "п", "p" },
{ "р", "r" }, { "с", "s" }, { "т", "t" }, { "у", "u" }, { "ф", "f" },
{ "х", "kh" }, { "ц", "ts" }, { "ч", "ch" }, { "ш", "sh" }, { "щ", "sch" },
{ "ъ", "" }, { "ы", "y" }, { "ь", "" }, { "э", "e" }, { "ю", "yu" },
{ "я", "ya" },
};
for (int i = 0; i < charmap.GetLength(0); i++)
{
input = input.Replace(charmap[i, 0], charmap[i, 1]);
}
return input;
}
/// <summary>
/// Replace special characters and patterns
/// </summary>
/// <param name="input">String to be parsed</param>
/// <returns>String with characters replaced</returns>
public static string SearchPattern(string input)
{
string[,] charmap = {
{ @"~", " - " },
{ @"_", " " },
{ @":", " " },
{ @">", ")" },
{ @"<", "(" },
{ @"\|", "-" },
{ "\"", "'" },
{ @"\*", "." },
{ @"\\", "-" },
{ @"/", "-" },
{ @"\?", " " },
{ @"\(([^)(]*)\(([^)]*)\)([^)(]*)\)", " " },
{ @"\(([^)]+)\)", " " },
{ @"\[([^]]+)\]", " " },
{ @"\{([^}]+)\}", " " },
{ @"(ZZZJUNK|ZZZ-UNK-|ZZZ-UNK |zzz unknow |zzz unk |Copy of |[.][a-z]{3}[.][a-z]{3}[.]|[.][a-z]{3}[.])", " " },
{ @" (r|rev|v|ver)\s*[\d\.]+[^\s]*", " " },
{ @"(( )|(\A))(\d{6}|\d{8})(( )|(\Z))", " " },
{ @"(( )|(\A))(\d{1,2})-(\d{1,2})-(\d{4}|\d{2})", " " },
{ @"(( )|(\A))(\d{4}|\d{2})-(\d{1,2})-(\d{1,2})", " " },
{ @"[-]+", "-" },
{ @"\A\s*\)", " " },
{ @"\A\s*(,|-)", " " },
{ @"\s+", " " },
{ @"\s+,", "," },
{ @"\s*(,|-)\s*\Z", " " },
};
for (int i = 0; i < charmap.GetLength(0); i++)
{
input = Regex.Replace(input, charmap[i, 0], charmap[i, 1]);
}
return input;
}
#endregion
#region String Manipulation
/// <summary>
/// Compare strings as numeric
/// </summary>
/// <param name="s1">First string to compare</param>
/// <param name="s2">Second string to compare</param>
/// <returns>-1 if s1 comes before s2, 0 if s1 and s2 are equal, 1 if s1 comes after s2</returns>
/// <remarks>I want to be able to handle paths properly with no issue, can I do a recursive call based on separated by path separator?</remarks>
public static int CompareNumeric(string s1, string s2)
{
// Save the orginal strings, for later comparison
string s1orig = s1;
string s2orig = s2;
// We want to normalize the strings, so we set both to lower case
s1 = s1.ToLowerInvariant();
s2 = s2.ToLowerInvariant();
// If the strings are the same exactly, return
if (s1 == s2)
{
return s1orig.CompareTo(s2orig);
}
// If one is null, then say that's less than
if (s1 == null)
{
return -1;
}
if (s2 == null)
{
return 1;
}
// Now split into path parts after converting AltDirSeparator to DirSeparator
s1 = s1.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
s2 = s2.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string[] s1parts = s1.Split(Path.DirectorySeparatorChar);
string[] s2parts = s2.Split(Path.DirectorySeparatorChar);
// Then compare each part in turn
for (int j = 0; j < s1parts.Length && j < s2parts.Length; j++)
{
int compared = CompareNumericPart(s1parts[j], s2parts[j]);
if (compared != 0)
{
return compared;
}
}
// If we got out here, then it looped through at least one of the strings
if (s1parts.Length > s2parts.Length)
{
return 1;
}
if (s1parts.Length < s2parts.Length)
{
return -1;
}
return s1orig.CompareTo(s2orig);
}
/// <summary>
/// Helper for CompareNumeric
/// </summary>
/// <param name="s1">First string to compare</param>
/// <param name="s2">Second string to compare</param>
/// <returns>-1 if s1 comes before s2, 0 if s1 and s2 are equal, 1 if s1 comes after s2</returns>
private static int CompareNumericPart(string s1, string s2)
{
// Otherwise, loop through until we have an answer
for (int i = 0; i < s1.Length && i < s2.Length; i++)
{
int s1c = s1[i];
int s2c = s2[i];
// If the characters are the same, continue
if (s1c == s2c)
{
continue;
}
// If they're different, check which one was larger
if (s1c > s2c)
{
return 1;
}
if (s1c < s2c)
{
return -1;
}
}
// If we got out here, then it looped through at least one of the strings
if (s1.Length > s2.Length)
{
return 1;
}
if (s1.Length < s2.Length)
{
return -1;
}
return 0;
}
/// <summary>
/// Convert all characters that are not considered XML-safe
/// </summary>
/// <param name="s">Input string to clean</param>
/// <returns>Cleaned string</returns>
public static string ConvertXMLUnsafeCharacters(string s)
{
return new String(s.Select(c =>
(c == 0x9
|| c == 0xA
|| c == 0xD
|| (c >= 0x20 && c <= 0xD77F)
|| (c >= 0xE000 && c <= 0xFFFD)
|| (c >= 0x10000 && c <= 0x10FFFF)
? c
: HttpUtility.HtmlEncode(c)[0]))
.ToArray());
}
/// <summary>
/// Get a proper romba sub path
/// </summary>
/// <param name="hash">SHA-1 hash to get the path for</param>
/// <returns>Subfolder path for the given hash</returns>
public static string GetRombaPath(string hash)
{
// If the hash isn't the right size, then we return null
if (hash.Length != Constants.SHA1Length) // TODO: When updating to SHA-256, this needs to update to Constants.SHA256Length
{
return null;
}
return Path.Combine(hash.Substring(0, 2), hash.Substring(2, 2), hash.Substring(4, 2), hash.Substring(6, 2), hash + ".gz");
}
/// <summary>
/// Get the multiplier to be used with the size given
/// </summary>
/// <param name="sizestring">String with possible size with extension</param>
/// <returns>Tuple of multiplier to use on final size and fixed size string</returns>
public static long GetSizeFromString(string sizestring)
{
// Make sure the string is in lower case
sizestring = sizestring.ToLowerInvariant();
// Get any trailing size identifiers
long multiplier = 1;
if (sizestring.EndsWith("k") || sizestring.EndsWith("kb"))
{
multiplier = Constants.KiloByte;
}
else if (sizestring.EndsWith("ki") || sizestring.EndsWith("kib"))
{
multiplier = Constants.KibiByte;
}
else if (sizestring.EndsWith("m") || sizestring.EndsWith("mb"))
{
multiplier = Constants.MegaByte;
}
else if (sizestring.EndsWith("mi") || sizestring.EndsWith("mib"))
{
multiplier = Constants.MibiByte;
}
else if (sizestring.EndsWith("g") || sizestring.EndsWith("gb"))
{
multiplier = Constants.GigaByte;
}
else if (sizestring.EndsWith("gi") || sizestring.EndsWith("gib"))
{
multiplier = Constants.GibiByte;
}
else if (sizestring.EndsWith("t") || sizestring.EndsWith("tb"))
{
multiplier = Constants.TeraByte;
}
else if (sizestring.EndsWith("ti") || sizestring.EndsWith("tib"))
{
multiplier = Constants.TibiByte;
}
else if (sizestring.EndsWith("p") || sizestring.EndsWith("pb"))
{
multiplier = Constants.PetaByte;
}
else if (sizestring.EndsWith("pi") || sizestring.EndsWith("pib"))
{
multiplier = Constants.PibiByte;
}
// Remove any trailing identifiers
sizestring = sizestring.TrimEnd(new char[] { 'k', 'm', 'g', 't', 'p', 'i', 'b', ' ' });
// Now try to get the size from the string
if (!Int64.TryParse(sizestring, out long size))
{
size = -1;
}
else
{
size *= multiplier;
}
return size;
}
/// <summary>
/// Get if a string contains Unicode characters
/// </summary>
/// <param name="s">Input string to test</param>
/// <returns>True if the string contains at least one Unicode character, false otherwise</returns>
public static bool IsUnicode(string s)
{
return (s.Any(c => c > 255));
}
/// <summary>
/// Remove all chars that are considered path unsafe
/// </summary>
/// <param name="s">Input string to clean</param>
/// <returns>Cleaned string</returns>
public static string RemovePathUnsafeCharacters(string s)
{
List<char> invalidPath = Path.GetInvalidPathChars().ToList();
return new string(s.Where(c => !invalidPath.Contains(c)).ToArray());
}
/// <summary>
/// Remove all unicode-specific chars from a string
/// </summary>
/// <param name="s">Input string to clean</param>
/// <returns>Cleaned string</returns>
public static string RemoveUnicodeCharacters(string s)
{
return new string(s.Where(c => c <= 255).ToArray());
}
/// <summary>
/// Split a line as if it were a CMP rom line
/// </summary>
/// <param name="s">Line to split</param>
/// <returns>Line split</returns>
/// <remarks>Uses code from http://stackoverflow.com/questions/554013/regular-expression-to-split-on-spaces-unless-in-quotes</remarks>
public static string[] SplitLineAsCMP(string s)
{
// Get the opening and closing brace locations
int openParenLoc = s.IndexOf('(');
int closeParenLoc = s.LastIndexOf(')');
// Now remove anything outside of those braces, including the braces
s = s.Substring(openParenLoc + 1, closeParenLoc - openParenLoc - 1);
s = s.Trim();
// Now we get each string, divided up as cleanly as possible
string[] matches = Regex
//.Matches(s, @"([^\s]*""[^""]+""[^\s]*)|[^""]?\w+[^""]?")
.Matches(s, @"[^\s""]+|""[^""]*""")
.Cast<Match>()
.Select(m => m.Groups[0].Value)
.ToArray();
return matches;
}
#endregion
#region Externally sourced methods
/// <summary>
/// Returns the human-readable file size for an arbitrary, 64-bit file size
/// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB"
/// </summary>
/// <param name="input"></param>
/// <returns>Human-readable file size</returns>
/// <link>http://www.somacon.com/p576.php</link>
public static string GetBytesReadable(long input)
{
// Get absolute value
long absolute_i = (input < 0 ? -input : input);
// Determine the suffix and readable value
string suffix;
double readable;
if (absolute_i >= 0x1000000000000000) // Exabyte
{
suffix = "EB";
readable = (input >> 50);
}
else if (absolute_i >= 0x4000000000000) // Petabyte
{
suffix = "PB";
readable = (input >> 40);
}
else if (absolute_i >= 0x10000000000) // Terabyte
{
suffix = "TB";
readable = (input >> 30);
}
else if (absolute_i >= 0x40000000) // Gigabyte
{
suffix = "GB";
readable = (input >> 20);
}
else if (absolute_i >= 0x100000) // Megabyte
{
suffix = "MB";
readable = (input >> 10);
}
else if (absolute_i >= 0x400) // Kilobyte
{
suffix = "KB";
readable = input;
}
else
{
return input.ToString("0 B"); // Byte
}
// Divide by 1024 to get fractional value
readable = (readable / 1024);
// Return formatted number with suffix
return readable.ToString("0.### ") + suffix;
}
/// <summary>
/// Convert a byte array to a hex string
/// </summary>
/// <param name="bytes">Byte array to convert</param>
/// <returns>Hex string representing the byte array</returns>
/// <link>http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa</link>
public static string ByteArrayToString(byte[] bytes)
{
try
{
string hex = BitConverter.ToString(bytes);
return hex.Replace("-", string.Empty).ToLowerInvariant();
}
catch
{
return null;
}
}
/// <summary>
/// Convert a hex string to a byte array
/// </summary>
/// <param name="hex">Hex string to convert</param>
/// <returns>Byte array represenging the hex string</returns>
/// <link>http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa</link>
public static byte[] StringToByteArray(string hex)
{
try
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
catch
{
return null;
}
}
/// <summary>
/// Convert a hex string to an ASCII one
/// </summary>
/// <param name="hexString">Hex string to convert</param>
/// <returns>ASCII string representing the hex string</returns>
/// <link>http://stackoverflow.com/questions/5613279/c-sharp-hex-to-ascii</link>
public static string ConvertHexToAscii(string hexString)
{
if (hexString.Contains("-"))
{
hexString = hexString.Replace("-", "");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
return sb.ToString();
}
/// <summary>
/// Convert an ASCII string to a hex one
/// </summary>
/// <param name="asciiString">ASCII string to convert</param>
/// <returns>Hex string representing the ASCII string</returns>
/// <link>http://stackoverflow.com/questions/15920741/convert-from-string-ascii-to-string-hex</link>
public static string ConvertAsciiToHex(string asciiString)
{
string hexOutput = "";
foreach (char _eachChar in asciiString.ToCharArray())
{
// Get the integral value of the character.
int value = Convert.ToInt32(_eachChar);
// Convert the decimal value to a hexadecimal value in string form.
hexOutput += String.Format("{0:X2}", value).Remove(0, 2);
// to make output as your eg
// hexOutput +=" "+ String.Format("{0:X}", value);
}
return hexOutput;
}
/// <summary>
/// Convert .NET DateTime to MS-DOS date format
/// </summary>
/// <param name="dateTime">.NET DateTime object to convert</param>
/// <returns>UInt32 representing the MS-DOS date</returns>
/// <remarks>
/// Adapted from 7-zip Source Code: CPP/Windows/TimeUtils.cpp:FileTimeToDosTime
/// </remarks>
public static uint ConvertDateTimeToMsDosTimeFormat(DateTime dateTime)
{
uint year = (uint)((dateTime.Year - 1980) % 128);
uint mon = (uint)dateTime.Month;
uint day = (uint)dateTime.Day;
uint hour = (uint)dateTime.Hour;
uint min = (uint)dateTime.Minute;
uint sec = (uint)dateTime.Second;
return (year << 25) | (mon << 21) | (day << 16) | (hour << 11) | (min << 5) | (sec >> 1);
}
/// <summary>
/// Convert MS-DOS date format to .NET DateTime
/// </summary>
/// <param name="msDosDateTime">UInt32 representing the MS-DOS date to convert</param>
/// <returns>.NET DateTime object representing the converted date</returns>
/// <remarks>
/// Adapted from 7-zip Source Code: CPP/Windows/TimeUtils.cpp:DosTimeToFileTime
/// </remarks>
public static DateTime ConvertMsDosTimeFormatToDateTime(uint msDosDateTime)
{
return new DateTime((int)(1980 + (msDosDateTime >> 25)), (int)((msDosDateTime >> 21) & 0xF), (int)((msDosDateTime >> 16) & 0x1F),
(int)((msDosDateTime >> 11) & 0x1F), (int)((msDosDateTime >> 5) & 0x3F), (int)((msDosDateTime & 0x1F) * 2));
}
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
/// <link>http://stackoverflow.com/questions/3825390/effective-way-to-find-any-files-encoding</link>
public static Encoding GetEncoding(string filename)
{
// Read the BOM
var bom = new byte[4];
FileStream file = FileTools.TryOpenRead(filename);
file.Read(bom, 0, 4);
file.Dispose();
// Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
return Encoding.Default;
}
/// <summary>
/// Extension method to get the DateTime that an assembly was linked
/// </summary>
/// <param name="assembly">Assembly to get linker time from</param>
/// <param name="target">Target timezone to convert the time to (default null)</param>
/// <returns>DateTime that the assembly was linked</returns>
/// <link>http://stackoverflow.com/questions/1600962/displaying-the-build-date</link>
public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null)
{
var filePath = assembly.Location;
const int c_PeHeaderOffset = 60;
const int c_LinkerTimestampOffset = 8;
var buffer = new byte[2048];
using (var stream = FileTools.TryOpenRead(filePath))
stream.Read(buffer, 0, 2048);
var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
var tz = target ?? TimeZoneInfo.Local;
var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz);
return localTime;
}
/// <summary>
/// Indicates whether the specified array is null or has a length of zero
/// </summary>
/// <param name="array">The array to test</param>
/// <returns>true if the array parameter is null or has a length of zero; otherwise, false.</returns>
/// <link>https://stackoverflow.com/questions/8560106/isnullorempty-equivalent-for-array-c-sharp</link>
public static bool IsNullOrEmpty(this Array array)
{
return (array == null || array.Length == 0);
}
#endregion
}
}

View File

@@ -1,7 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Schema;
@@ -37,9 +41,9 @@ using SharpCompress.Common;
namespace SabreTools.Library.Tools
{
/// <summary>
/// Tools for working with non-archive files and stream
/// Static utility functions used throughout the library
/// </summary>
public static class FileTools
public static class Utilities
{
#region BinaryReader Extensions
@@ -197,6 +201,238 @@ namespace SabreTools.Library.Tools
#endregion
#region DAT Cleaning
/// <summary>
/// Clean a game (or rom) name to the WoD standard
/// </summary>
/// <param name="game">Name of the game to be cleaned</param>
/// <returns>The cleaned name</returns>
public static string CleanGameName(string game)
{
///Run the name through the filters to make sure that it's correct
game = NormalizeChars(game);
game = RussianToLatin(game);
game = SearchPattern(game);
game = new Regex(@"(([[(].*[\)\]] )?([^([]+))").Match(game).Groups[1].Value;
game = game.TrimStart().TrimEnd();
return game;
}
/// <summary>
/// Clean a game (or rom) name to the WoD standard
/// </summary>
/// <param name="game">Array representing the path to be cleaned</param>
/// <returns>The cleaned name</returns>
public static string CleanGameName(string[] game)
{
game[game.Length - 1] = CleanGameName(game[game.Length - 1]);
string outgame = String.Join(Path.DirectorySeparatorChar.ToString(), game);
outgame = outgame.TrimStart().TrimEnd();
return outgame;
}
/// <summary>
/// Clean a hash string and pad to the correct size
/// </summary>
/// <param name="hash">Hash string to sanitize</param>
/// <param name="padding">Amount of characters to pad to</param>
/// <returns>Cleaned string</returns>
public static string CleanHashData(string hash, int padding)
{
// If we have a known blank hash, return blank
if (string.IsNullOrEmpty(hash) || hash == "-" || hash == "_")
{
return "";
}
// Check to see if it's a "hex" hash
hash = hash.Trim().Replace("0x", "");
// If we have a blank hash now, return blank
if (string.IsNullOrEmpty(hash))
{
return "";
}
// If the hash shorter than the required length, pad it
if (hash.Length < padding)
{
hash = hash.PadLeft(padding, '0');
}
// If the hash is longer than the required length, it's invalid
else if (hash.Length > padding)
{
return "";
}
// Now normalize the hash
hash = hash.ToLowerInvariant();
// Otherwise, make sure that every character is a proper match
for (int i = 0; i < hash.Length; i++)
{
if ((hash[i] < '0' || hash[i] > '9') && (hash[i] < 'a' || hash[i] > 'f'))
{
hash = "";
break;
}
}
return hash;
}
/// <summary>
/// Clean a hash string from a Listrom DAT
/// </summary>
/// <param name="hash">Hash string to sanitize</param>
/// <returns>Cleaned string</returns>
public static string CleanListromHashData(string hash)
{
if (hash.StartsWith("CRC"))
{
return hash.Substring(4, 8).ToLowerInvariant();
}
else if (hash.StartsWith("SHA1"))
{
return hash.Substring(5, 40).ToLowerInvariant();
}
return hash;
}
/// <summary>
/// Replace accented characters
/// </summary>
/// <param name="input">String to be parsed</param>
/// <returns>String with characters replaced</returns>
public static string NormalizeChars(string input)
{
string[,] charmap = {
{ "Á", "A" }, { "á", "a" },
{ "À", "A" }, { "à", "a" },
{ "Â", "A" }, { "â", "a" },
{ "Ä", "Ae" }, { "ä", "ae" },
{ "Ã", "A" }, { "ã", "a" },
{ "Å", "A" }, { "å", "a" },
{ "Æ", "Ae" }, { "æ", "ae" },
{ "Ç", "C" }, { "ç", "c" },
{ "Ð", "D" }, { "ð", "d" },
{ "É", "E" }, { "é", "e" },
{ "È", "E" }, { "è", "e" },
{ "Ê", "E" }, { "ê", "e" },
{ "Ë", "E" }, { "ë", "e" },
{ "ƒ", "f" },
{ "Í", "I" }, { "í", "i" },
{ "Ì", "I" }, { "ì", "i" },
{ "Î", "I" }, { "î", "i" },
{ "Ï", "I" }, { "ï", "i" },
{ "Ñ", "N" }, { "ñ", "n" },
{ "Ó", "O" }, { "ó", "o" },
{ "Ò", "O" }, { "ò", "o" },
{ "Ô", "O" }, { "ô", "o" },
{ "Ö", "Oe" }, { "ö", "oe" },
{ "Õ", "O" }, { "õ", "o" },
{ "Ø", "O" }, { "ø", "o" },
{ "Š", "S" }, { "š", "s" },
{ "ß", "ss" },
{ "Þ", "B" }, { "þ", "b" },
{ "Ú", "U" }, { "ú", "u" },
{ "Ù", "U" }, { "ù", "u" },
{ "Û", "U" }, { "û", "u" },
{ "Ü", "Ue" }, { "ü", "ue" },
{ "ÿ", "y" },
{ "Ý", "Y" }, { "ý", "y" },
{ "Ž", "Z" }, { "ž", "z" },
};
for (int i = 0; i < charmap.GetLength(0); i++)
{
input = input.Replace(charmap[i, 0], charmap[i, 1]);
}
return input;
}
/// <summary>
/// Convert Cyrillic lettering to Latin lettering
/// </summary>
/// <param name="input">String to be parsed</param>
/// <returns>String with characters replaced</returns>
public static string RussianToLatin(string input)
{
string[,] charmap = {
{ "А", "A" }, { "Б", "B" }, { "В", "V" }, { "Г", "G" }, { "Д", "D" },
{ "Е", "E" }, { "Ё", "Yo" }, { "Ж", "Zh" }, { "З", "Z" }, { "И", "I" },
{ "Й", "J" }, { "К", "K" }, { "Л", "L" }, { "М", "M" }, { "Н", "N" },
{ "О", "O" }, { "П", "P" }, { "Р", "R" }, { "С", "S" }, { "Т", "T" },
{ "У", "U" }, { "Ф", "f" }, { "Х", "Kh" }, { "Ц", "Ts" }, { "Ч", "Ch" },
{ "Ш", "Sh" }, { "Щ", "Sch" }, { "Ъ", "" }, { "Ы", "y" }, { "Ь", "" },
{ "Э", "e" }, { "Ю", "yu" }, { "Я", "ya" }, { "а", "a" }, { "б", "b" },
{ "в", "v" }, { "г", "g" }, { "д", "d" }, { "е", "e" }, { "ё", "yo" },
{ "ж", "zh" }, { "з", "z" }, { "и", "i" }, { "й", "j" }, { "к", "k" },
{ "л", "l" }, { "м", "m" }, { "н", "n" }, { "о", "o" }, { "п", "p" },
{ "р", "r" }, { "с", "s" }, { "т", "t" }, { "у", "u" }, { "ф", "f" },
{ "х", "kh" }, { "ц", "ts" }, { "ч", "ch" }, { "ш", "sh" }, { "щ", "sch" },
{ "ъ", "" }, { "ы", "y" }, { "ь", "" }, { "э", "e" }, { "ю", "yu" },
{ "я", "ya" },
};
for (int i = 0; i < charmap.GetLength(0); i++)
{
input = input.Replace(charmap[i, 0], charmap[i, 1]);
}
return input;
}
/// <summary>
/// Replace special characters and patterns
/// </summary>
/// <param name="input">String to be parsed</param>
/// <returns>String with characters replaced</returns>
public static string SearchPattern(string input)
{
string[,] charmap = {
{ @"~", " - " },
{ @"_", " " },
{ @":", " " },
{ @">", ")" },
{ @"<", "(" },
{ @"\|", "-" },
{ "\"", "'" },
{ @"\*", "." },
{ @"\\", "-" },
{ @"/", "-" },
{ @"\?", " " },
{ @"\(([^)(]*)\(([^)]*)\)([^)(]*)\)", " " },
{ @"\(([^)]+)\)", " " },
{ @"\[([^]]+)\]", " " },
{ @"\{([^}]+)\}", " " },
{ @"(ZZZJUNK|ZZZ-UNK-|ZZZ-UNK |zzz unknow |zzz unk |Copy of |[.][a-z]{3}[.][a-z]{3}[.]|[.][a-z]{3}[.])", " " },
{ @" (r|rev|v|ver)\s*[\d\.]+[^\s]*", " " },
{ @"(( )|(\A))(\d{6}|\d{8})(( )|(\Z))", " " },
{ @"(( )|(\A))(\d{1,2})-(\d{1,2})-(\d{4}|\d{2})", " " },
{ @"(( )|(\A))(\d{4}|\d{2})-(\d{1,2})-(\d{1,2})", " " },
{ @"[-]+", "-" },
{ @"\A\s*\)", " " },
{ @"\A\s*(,|-)", " " },
{ @"\s+", " " },
{ @"\s+,", "," },
{ @"\s*(,|-)\s*\Z", " " },
};
for (int i = 0; i < charmap.GetLength(0); i++)
{
input = Regex.Replace(input, charmap[i, 0], charmap[i, 1]);
}
return input;
}
#endregion
#region Factories
/// <summary>
@@ -390,7 +626,7 @@ namespace SabreTools.Library.Tools
/// </remarks>
public static DatItem GetCHDInfo(string input)
{
FileStream fs = FileTools.TryOpenRead(input);
FileStream fs = TryOpenRead(input);
DatItem datItem = GetCHDInfo(fs);
fs.Dispose();
return datItem;
@@ -429,7 +665,7 @@ namespace SabreTools.Library.Tools
try
{
byte[] magic = new byte[8];
BinaryReader br = new BinaryReader(FileTools.TryOpenRead(input));
BinaryReader br = new BinaryReader(TryOpenRead(input));
magic = br.ReadBytes(8);
br.Dispose();
@@ -664,7 +900,7 @@ namespace SabreTools.Library.Tools
{
// Create the input and output streams
MemoryStream outputStream = new MemoryStream();
FileStream inputStream = FileTools.TryOpenRead(input);
FileStream inputStream = TryOpenRead(input);
// Transform the stream and get the information from it
rule.TransformStream(inputStream, outputStream, keepReadOpen: false, keepWriteOpen: true);
@@ -876,7 +1112,7 @@ namespace SabreTools.Library.Tools
// Extract the header as a string for the database
byte[] hbin = br.ReadBytes((int)rule.StartOffset);
hstr = Style.ByteArrayToString(hbin);
hstr = ByteArrayToString(hbin);
br.Dispose();
// Apply the rule to the file
@@ -912,7 +1148,7 @@ namespace SabreTools.Library.Tools
{
if (Directory.Exists(input))
{
List<string> files = FileTools.RetrieveFiles(input, new List<string>());
List<string> files = RetrieveFiles(input, new List<string>());
foreach (string file in files)
{
try
@@ -1352,27 +1588,27 @@ namespace SabreTools.Library.Tools
if ((omitFromScan & Hash.MD5) == 0)
{
md5.TransformFinalBlock(buffer, 0, 0);
rom.MD5 = Style.ByteArrayToString(md5.Hash);
rom.MD5 = ByteArrayToString(md5.Hash);
}
if ((omitFromScan & Hash.SHA1) == 0)
{
sha1.TransformFinalBlock(buffer, 0, 0);
rom.SHA1 = Style.ByteArrayToString(sha1.Hash);
rom.SHA1 = ByteArrayToString(sha1.Hash);
}
if ((omitFromScan & Hash.SHA256) == 0)
{
sha256.TransformFinalBlock(buffer, 0, 0);
rom.SHA256 = Style.ByteArrayToString(sha256.Hash);
rom.SHA256 = ByteArrayToString(sha256.Hash);
}
if ((omitFromScan & Hash.SHA384) == 0)
{
sha384.TransformFinalBlock(buffer, 0, 0);
rom.SHA384 = Style.ByteArrayToString(sha384.Hash);
rom.SHA384 = ByteArrayToString(sha384.Hash);
}
if ((omitFromScan & Hash.SHA512) == 0)
{
sha512.TransformFinalBlock(buffer, 0, 0);
rom.SHA512 = Style.ByteArrayToString(sha512.Hash);
rom.SHA512 = ByteArrayToString(sha512.Hash);
}
if ((omitFromScan & Hash.xxHash) == 0)
{
@@ -1436,7 +1672,7 @@ namespace SabreTools.Library.Tools
byte[] sha1 = chd.GetSHA1FromHeader();
// Set the SHA-1 of the Disk to return
datItem.SHA1 = (sha1 == null ? null : Style.ByteArrayToString(sha1));
datItem.SHA1 = (sha1 == null ? null : ByteArrayToString(sha1));
return datItem;
}
@@ -1498,5 +1734,521 @@ namespace SabreTools.Library.Tools
}
#endregion
#region String Manipulation
/// <summary>
/// Compare strings as numeric
/// </summary>
/// <param name="s1">First string to compare</param>
/// <param name="s2">Second string to compare</param>
/// <returns>-1 if s1 comes before s2, 0 if s1 and s2 are equal, 1 if s1 comes after s2</returns>
/// <remarks>I want to be able to handle paths properly with no issue, can I do a recursive call based on separated by path separator?</remarks>
public static int CompareNumeric(string s1, string s2)
{
// Save the orginal strings, for later comparison
string s1orig = s1;
string s2orig = s2;
// We want to normalize the strings, so we set both to lower case
s1 = s1.ToLowerInvariant();
s2 = s2.ToLowerInvariant();
// If the strings are the same exactly, return
if (s1 == s2)
{
return s1orig.CompareTo(s2orig);
}
// If one is null, then say that's less than
if (s1 == null)
{
return -1;
}
if (s2 == null)
{
return 1;
}
// Now split into path parts after converting AltDirSeparator to DirSeparator
s1 = s1.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
s2 = s2.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
string[] s1parts = s1.Split(Path.DirectorySeparatorChar);
string[] s2parts = s2.Split(Path.DirectorySeparatorChar);
// Then compare each part in turn
for (int j = 0; j < s1parts.Length && j < s2parts.Length; j++)
{
int compared = CompareNumericPart(s1parts[j], s2parts[j]);
if (compared != 0)
{
return compared;
}
}
// If we got out here, then it looped through at least one of the strings
if (s1parts.Length > s2parts.Length)
{
return 1;
}
if (s1parts.Length < s2parts.Length)
{
return -1;
}
return s1orig.CompareTo(s2orig);
}
/// <summary>
/// Helper for CompareNumeric
/// </summary>
/// <param name="s1">First string to compare</param>
/// <param name="s2">Second string to compare</param>
/// <returns>-1 if s1 comes before s2, 0 if s1 and s2 are equal, 1 if s1 comes after s2</returns>
private static int CompareNumericPart(string s1, string s2)
{
// Otherwise, loop through until we have an answer
for (int i = 0; i < s1.Length && i < s2.Length; i++)
{
int s1c = s1[i];
int s2c = s2[i];
// If the characters are the same, continue
if (s1c == s2c)
{
continue;
}
// If they're different, check which one was larger
if (s1c > s2c)
{
return 1;
}
if (s1c < s2c)
{
return -1;
}
}
// If we got out here, then it looped through at least one of the strings
if (s1.Length > s2.Length)
{
return 1;
}
if (s1.Length < s2.Length)
{
return -1;
}
return 0;
}
/// <summary>
/// Convert all characters that are not considered XML-safe
/// </summary>
/// <param name="s">Input string to clean</param>
/// <returns>Cleaned string</returns>
public static string ConvertXMLUnsafeCharacters(string s)
{
return new String(s.Select(c =>
(c == 0x9
|| c == 0xA
|| c == 0xD
|| (c >= 0x20 && c <= 0xD77F)
|| (c >= 0xE000 && c <= 0xFFFD)
|| (c >= 0x10000 && c <= 0x10FFFF)
? c
: HttpUtility.HtmlEncode(c)[0]))
.ToArray());
}
/// <summary>
/// Get a proper romba sub path
/// </summary>
/// <param name="hash">SHA-1 hash to get the path for</param>
/// <returns>Subfolder path for the given hash</returns>
public static string GetRombaPath(string hash)
{
// If the hash isn't the right size, then we return null
if (hash.Length != Constants.SHA1Length) // TODO: When updating to SHA-256, this needs to update to Constants.SHA256Length
{
return null;
}
return Path.Combine(hash.Substring(0, 2), hash.Substring(2, 2), hash.Substring(4, 2), hash.Substring(6, 2), hash + ".gz");
}
/// <summary>
/// Get the multiplier to be used with the size given
/// </summary>
/// <param name="sizestring">String with possible size with extension</param>
/// <returns>Tuple of multiplier to use on final size and fixed size string</returns>
public static long GetSizeFromString(string sizestring)
{
// Make sure the string is in lower case
sizestring = sizestring.ToLowerInvariant();
// Get any trailing size identifiers
long multiplier = 1;
if (sizestring.EndsWith("k") || sizestring.EndsWith("kb"))
{
multiplier = Constants.KiloByte;
}
else if (sizestring.EndsWith("ki") || sizestring.EndsWith("kib"))
{
multiplier = Constants.KibiByte;
}
else if (sizestring.EndsWith("m") || sizestring.EndsWith("mb"))
{
multiplier = Constants.MegaByte;
}
else if (sizestring.EndsWith("mi") || sizestring.EndsWith("mib"))
{
multiplier = Constants.MibiByte;
}
else if (sizestring.EndsWith("g") || sizestring.EndsWith("gb"))
{
multiplier = Constants.GigaByte;
}
else if (sizestring.EndsWith("gi") || sizestring.EndsWith("gib"))
{
multiplier = Constants.GibiByte;
}
else if (sizestring.EndsWith("t") || sizestring.EndsWith("tb"))
{
multiplier = Constants.TeraByte;
}
else if (sizestring.EndsWith("ti") || sizestring.EndsWith("tib"))
{
multiplier = Constants.TibiByte;
}
else if (sizestring.EndsWith("p") || sizestring.EndsWith("pb"))
{
multiplier = Constants.PetaByte;
}
else if (sizestring.EndsWith("pi") || sizestring.EndsWith("pib"))
{
multiplier = Constants.PibiByte;
}
// Remove any trailing identifiers
sizestring = sizestring.TrimEnd(new char[] { 'k', 'm', 'g', 't', 'p', 'i', 'b', ' ' });
// Now try to get the size from the string
if (!Int64.TryParse(sizestring, out long size))
{
size = -1;
}
else
{
size *= multiplier;
}
return size;
}
/// <summary>
/// Get if a string contains Unicode characters
/// </summary>
/// <param name="s">Input string to test</param>
/// <returns>True if the string contains at least one Unicode character, false otherwise</returns>
public static bool IsUnicode(string s)
{
return (s.Any(c => c > 255));
}
/// <summary>
/// Remove all chars that are considered path unsafe
/// </summary>
/// <param name="s">Input string to clean</param>
/// <returns>Cleaned string</returns>
public static string RemovePathUnsafeCharacters(string s)
{
List<char> invalidPath = Path.GetInvalidPathChars().ToList();
return new string(s.Where(c => !invalidPath.Contains(c)).ToArray());
}
/// <summary>
/// Remove all unicode-specific chars from a string
/// </summary>
/// <param name="s">Input string to clean</param>
/// <returns>Cleaned string</returns>
public static string RemoveUnicodeCharacters(string s)
{
return new string(s.Where(c => c <= 255).ToArray());
}
/// <summary>
/// Split a line as if it were a CMP rom line
/// </summary>
/// <param name="s">Line to split</param>
/// <returns>Line split</returns>
/// <remarks>Uses code from http://stackoverflow.com/questions/554013/regular-expression-to-split-on-spaces-unless-in-quotes</remarks>
public static string[] SplitLineAsCMP(string s)
{
// Get the opening and closing brace locations
int openParenLoc = s.IndexOf('(');
int closeParenLoc = s.LastIndexOf(')');
// Now remove anything outside of those braces, including the braces
s = s.Substring(openParenLoc + 1, closeParenLoc - openParenLoc - 1);
s = s.Trim();
// Now we get each string, divided up as cleanly as possible
string[] matches = Regex
//.Matches(s, @"([^\s]*""[^""]+""[^\s]*)|[^""]?\w+[^""]?")
.Matches(s, @"[^\s""]+|""[^""]*""")
.Cast<Match>()
.Select(m => m.Groups[0].Value)
.ToArray();
return matches;
}
#endregion
#region *Externally sourced methods*
/// <summary>
/// Returns the human-readable file size for an arbitrary, 64-bit file size
/// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB"
/// </summary>
/// <param name="input"></param>
/// <returns>Human-readable file size</returns>
/// <link>http://www.somacon.com/p576.php</link>
public static string GetBytesReadable(long input)
{
// Get absolute value
long absolute_i = (input < 0 ? -input : input);
// Determine the suffix and readable value
string suffix;
double readable;
if (absolute_i >= 0x1000000000000000) // Exabyte
{
suffix = "EB";
readable = (input >> 50);
}
else if (absolute_i >= 0x4000000000000) // Petabyte
{
suffix = "PB";
readable = (input >> 40);
}
else if (absolute_i >= 0x10000000000) // Terabyte
{
suffix = "TB";
readable = (input >> 30);
}
else if (absolute_i >= 0x40000000) // Gigabyte
{
suffix = "GB";
readable = (input >> 20);
}
else if (absolute_i >= 0x100000) // Megabyte
{
suffix = "MB";
readable = (input >> 10);
}
else if (absolute_i >= 0x400) // Kilobyte
{
suffix = "KB";
readable = input;
}
else
{
return input.ToString("0 B"); // Byte
}
// Divide by 1024 to get fractional value
readable = (readable / 1024);
// Return formatted number with suffix
return readable.ToString("0.### ") + suffix;
}
/// <summary>
/// Convert a byte array to a hex string
/// </summary>
/// <param name="bytes">Byte array to convert</param>
/// <returns>Hex string representing the byte array</returns>
/// <link>http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa</link>
public static string ByteArrayToString(byte[] bytes)
{
try
{
string hex = BitConverter.ToString(bytes);
return hex.Replace("-", string.Empty).ToLowerInvariant();
}
catch
{
return null;
}
}
/// <summary>
/// Convert a hex string to a byte array
/// </summary>
/// <param name="hex">Hex string to convert</param>
/// <returns>Byte array represenging the hex string</returns>
/// <link>http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa</link>
public static byte[] StringToByteArray(string hex)
{
try
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
catch
{
return null;
}
}
/// <summary>
/// Convert a hex string to an ASCII one
/// </summary>
/// <param name="hexString">Hex string to convert</param>
/// <returns>ASCII string representing the hex string</returns>
/// <link>http://stackoverflow.com/questions/5613279/c-sharp-hex-to-ascii</link>
public static string ConvertHexToAscii(string hexString)
{
if (hexString.Contains("-"))
{
hexString = hexString.Replace("-", "");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
return sb.ToString();
}
/// <summary>
/// Convert an ASCII string to a hex one
/// </summary>
/// <param name="asciiString">ASCII string to convert</param>
/// <returns>Hex string representing the ASCII string</returns>
/// <link>http://stackoverflow.com/questions/15920741/convert-from-string-ascii-to-string-hex</link>
public static string ConvertAsciiToHex(string asciiString)
{
string hexOutput = "";
foreach (char _eachChar in asciiString.ToCharArray())
{
// Get the integral value of the character.
int value = Convert.ToInt32(_eachChar);
// Convert the decimal value to a hexadecimal value in string form.
hexOutput += String.Format("{0:X2}", value).Remove(0, 2);
// to make output as your eg
// hexOutput +=" "+ String.Format("{0:X}", value);
}
return hexOutput;
}
/// <summary>
/// Convert .NET DateTime to MS-DOS date format
/// </summary>
/// <param name="dateTime">.NET DateTime object to convert</param>
/// <returns>UInt32 representing the MS-DOS date</returns>
/// <remarks>
/// Adapted from 7-zip Source Code: CPP/Windows/TimeUtils.cpp:FileTimeToDosTime
/// </remarks>
public static uint ConvertDateTimeToMsDosTimeFormat(DateTime dateTime)
{
uint year = (uint)((dateTime.Year - 1980) % 128);
uint mon = (uint)dateTime.Month;
uint day = (uint)dateTime.Day;
uint hour = (uint)dateTime.Hour;
uint min = (uint)dateTime.Minute;
uint sec = (uint)dateTime.Second;
return (year << 25) | (mon << 21) | (day << 16) | (hour << 11) | (min << 5) | (sec >> 1);
}
/// <summary>
/// Convert MS-DOS date format to .NET DateTime
/// </summary>
/// <param name="msDosDateTime">UInt32 representing the MS-DOS date to convert</param>
/// <returns>.NET DateTime object representing the converted date</returns>
/// <remarks>
/// Adapted from 7-zip Source Code: CPP/Windows/TimeUtils.cpp:DosTimeToFileTime
/// </remarks>
public static DateTime ConvertMsDosTimeFormatToDateTime(uint msDosDateTime)
{
return new DateTime((int)(1980 + (msDosDateTime >> 25)), (int)((msDosDateTime >> 21) & 0xF), (int)((msDosDateTime >> 16) & 0x1F),
(int)((msDosDateTime >> 11) & 0x1F), (int)((msDosDateTime >> 5) & 0x3F), (int)((msDosDateTime & 0x1F) * 2));
}
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
/// <link>http://stackoverflow.com/questions/3825390/effective-way-to-find-any-files-encoding</link>
public static Encoding GetEncoding(string filename)
{
// Read the BOM
var bom = new byte[4];
FileStream file = TryOpenRead(filename);
file.Read(bom, 0, 4);
file.Dispose();
// Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
return Encoding.Default;
}
/// <summary>
/// Extension method to get the DateTime that an assembly was linked
/// </summary>
/// <param name="assembly">Assembly to get linker time from</param>
/// <param name="target">Target timezone to convert the time to (default null)</param>
/// <returns>DateTime that the assembly was linked</returns>
/// <link>http://stackoverflow.com/questions/1600962/displaying-the-build-date</link>
public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null)
{
var filePath = assembly.Location;
const int c_PeHeaderOffset = 60;
const int c_LinkerTimestampOffset = 8;
var buffer = new byte[2048];
using (var stream = TryOpenRead(filePath))
stream.Read(buffer, 0, 2048);
var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);
var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset);
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var linkTimeUtc = epoch.AddSeconds(secondsSince1970);
var tz = target ?? TimeZoneInfo.Local;
var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz);
return localTime;
}
/// <summary>
/// Indicates whether the specified array is null or has a length of zero
/// </summary>
/// <param name="array">The array to test</param>
/// <returns>true if the array parameter is null or has a length of zero; otherwise, false.</returns>
/// <link>https://stackoverflow.com/questions/8560106/isnullorempty-equivalent-for-array-c-sharp</link>
public static bool IsNullOrEmpty(this Array array)
{
return (array == null || array.Length == 0);
}
#endregion
}
}

View File

@@ -167,13 +167,13 @@ namespace SabreTools
{
if (File.Exists(input))
{
FileTools.DetectSkipperAndTransform(input, outDir, nostore);
Utilities.DetectSkipperAndTransform(input, outDir, nostore);
}
else if (Directory.Exists(input))
{
foreach (string sub in Directory.EnumerateFiles(input, "*", SearchOption.AllDirectories))
{
FileTools.DetectSkipperAndTransform(sub, outDir, nostore);
Utilities.DetectSkipperAndTransform(sub, outDir, nostore);
}
}
}
@@ -263,13 +263,13 @@ namespace SabreTools
{
if (File.Exists(input))
{
FileTools.RestoreHeader(input, outDir);
Utilities.RestoreHeader(input, outDir);
}
else if (Directory.Exists(input))
{
foreach (string sub in Directory.EnumerateFiles(input, "*", SearchOption.AllDirectories))
{
FileTools.RestoreHeader(sub, outDir);
Utilities.RestoreHeader(sub, outDir);
}
}
}
@@ -338,10 +338,10 @@ namespace SabreTools
SplitType splitType, bool chdsAsFiles)
{
// Get the archive scanning level
ArchiveScanLevel asl = FileTools.GetArchiveScanLevelFromNumbers(sevenzip, gz, rar, zip);
ArchiveScanLevel asl = Utilities.GetArchiveScanLevelFromNumbers(sevenzip, gz, rar, zip);
// Get a list of files from the input datfiles
datfiles = FileTools.GetOnlyFilesFromInputs(datfiles);
datfiles = Utilities.GetOnlyFilesFromInputs(datfiles);
InternalStopwatch watch = new InternalStopwatch("Populating internal DAT");
@@ -378,7 +378,7 @@ namespace SabreTools
InternalStopwatch watch = new InternalStopwatch("Populating internal DAT");
// Get a list of files from the input datfiles
datfiles = FileTools.GetOnlyFilesFromInputs(datfiles);
datfiles = Utilities.GetOnlyFilesFromInputs(datfiles);
// Add all of the input DATs into one huge internal DAT
DatFile datdata = new DatFile();
@@ -749,10 +749,10 @@ namespace SabreTools
string headerToCheckAgainst, SplitType splitType, bool chdsAsFiles)
{
// Get the archive scanning level
ArchiveScanLevel asl = FileTools.GetArchiveScanLevelFromNumbers(1, 1, 1, 1);
ArchiveScanLevel asl = Utilities.GetArchiveScanLevelFromNumbers(1, 1, 1, 1);
// Get a list of files from the input datfiles
datfiles = FileTools.GetOnlyFilesFromInputs(datfiles);
datfiles = Utilities.GetOnlyFilesFromInputs(datfiles);
InternalStopwatch watch = new InternalStopwatch("Populating internal DAT");
@@ -780,7 +780,7 @@ namespace SabreTools
InternalStopwatch watch = new InternalStopwatch("Populating internal DAT");
// Get a list of files from the input datfiles
datfiles = FileTools.GetOnlyFilesFromInputs(datfiles);
datfiles = Utilities.GetOnlyFilesFromInputs(datfiles);
// Add all of the input DATs into one huge internal DAT
DatFile datdata = new DatFile();

View File

@@ -892,11 +892,11 @@ namespace SabreTools
break;
case "-seq":
case "--equal":
filter.SizeEqualTo = Style.GetSizeFromString(args[++i]);
filter.SizeEqualTo = Utilities.GetSizeFromString(args[++i]);
break;
case "-sgt":
case "--greater":
filter.SizeGreaterThanOrEqual = Style.GetSizeFromString(args[++i]);
filter.SizeGreaterThanOrEqual = Utilities.GetSizeFromString(args[++i]);
break;
case "-sha1":
case "--sha1":
@@ -916,7 +916,7 @@ namespace SabreTools
break;
case "-slt":
case "--less":
filter.SizeLessThanOrEqual = Style.GetSizeFromString(args[++i]);
filter.SizeLessThanOrEqual = Utilities.GetSizeFromString(args[++i]);
break;
case "-t":
case "--temp":
@@ -1171,11 +1171,11 @@ namespace SabreTools
break;
case "-seq":
case "--equal":
filter.SizeEqualTo = Style.GetSizeFromString(split[1]);
filter.SizeEqualTo = Utilities.GetSizeFromString(split[1]);
break;
case "-sgt":
case "--greater":
filter.SizeGreaterThanOrEqual = Style.GetSizeFromString(split[1]);
filter.SizeGreaterThanOrEqual = Utilities.GetSizeFromString(split[1]);
break;
case "-sha1":
case "--sha1":
@@ -1195,7 +1195,7 @@ namespace SabreTools
break;
case "-slt":
case "--less":
filter.SizeLessThanOrEqual = Style.GetSizeFromString(split[1]);
filter.SizeLessThanOrEqual = Utilities.GetSizeFromString(split[1]);
break;
case "-t":
case "--temp":