[FileTools] Create and use safe file accessors

This commit is contained in:
Matt Nadareski
2017-03-15 20:07:28 -07:00
parent 26d49d9e19
commit e7f3192476
11 changed files with 197 additions and 88 deletions

View File

@@ -14,8 +14,6 @@ using System.IO;
#else #else
using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Filesystem;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using SearchOption = System.IO.SearchOption; using SearchOption = System.IO.SearchOption;
using StreamWriter = System.IO.StreamWriter; using StreamWriter = System.IO.StreamWriter;
#endif #endif
@@ -85,7 +83,7 @@ namespace RombaSharp
{ {
SqliteConnection dbc = new SqliteConnection(_connectionString); SqliteConnection dbc = new SqliteConnection(_connectionString);
dbc.Open(); dbc.Open();
StreamWriter sw = new StreamWriter(File.Open("export.csv", FileMode.Create, FileAccess.Write)); StreamWriter sw = new StreamWriter(FileTools.TryCreate("export.csv"));
sw.WriteLine("\"ID\",\"Size\",\"CRC\",\"MD5\",\"SHA-1\",\"In Depot\",\"DAT Hash\""); sw.WriteLine("\"ID\",\"Size\",\"CRC\",\"MD5\",\"SHA-1\",\"In Depot\",\"DAT Hash\"");

View File

@@ -151,7 +151,7 @@ namespace SabreTools.Helper.Dats
Globals.Logger.User("Cleaning temp folder"); Globals.Logger.User("Cleaning temp folder");
if (tempDir != Path.GetTempPath()) if (tempDir != Path.GetTempPath())
{ {
FileTools.SafeTryDeleteDirectory(tempDir); FileTools.TryDeleteDirectory(tempDir);
} }
return true; return true;
@@ -326,11 +326,11 @@ namespace SabreTools.Helper.Dats
// Cue to delete the file if it's a copy // Cue to delete the file if it's a copy
if (copyFiles && item != newItem) if (copyFiles && item != newItem)
{ {
FileTools.SafeTryDeleteDirectory(newBasePath); FileTools.TryDeleteDirectory(newBasePath);
} }
// Delete the sub temp directory // Delete the sub temp directory
FileTools.SafeTryDeleteDirectory(tempSubDir); FileTools.TryDeleteDirectory(tempSubDir);
} }
/// <summary> /// <summary>

View File

@@ -226,7 +226,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
sr.ReadLine(); // Skip the first line since it's the header sr.ReadLine(); // Skip the first line since it's the header
while (!sr.EndOfStream) while (!sr.EndOfStream)
@@ -317,7 +317,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
bool block = false, superdat = false; bool block = false, superdat = false;
string blockname = "", tempgamename = "", gamedesc = "", cloneof = "", string blockname = "", tempgamename = "", gamedesc = "", cloneof = "",
@@ -933,7 +933,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
// Create an empty list of columns to parse though // Create an empty list of columns to parse though
List<string> columns = new List<string>(); List<string> columns = new List<string>();
@@ -2441,7 +2441,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream) while (!sr.EndOfStream)
{ {
@@ -2500,7 +2500,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream) while (!sr.EndOfStream)
{ {
@@ -2559,7 +2559,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream) while (!sr.EndOfStream)
{ {
@@ -2618,7 +2618,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream) while (!sr.EndOfStream)
{ {
@@ -2677,7 +2677,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream) while (!sr.EndOfStream)
{ {
@@ -2736,7 +2736,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
while (!sr.EndOfStream) while (!sr.EndOfStream)
{ {
@@ -2797,7 +2797,7 @@ namespace SabreTools.Helper.Dats
{ {
// Open a file reader // Open a file reader
Encoding enc = Style.GetEncoding(filename); Encoding enc = Style.GetEncoding(filename);
StreamReader sr = new StreamReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), enc); StreamReader sr = new StreamReader(FileTools.TryOpenRead(filename), enc);
string blocktype = ""; string blocktype = "";
while (!sr.EndOfStream) while (!sr.EndOfStream)

View File

@@ -447,7 +447,7 @@ namespace SabreTools.Helper.Dats
try try
{ {
Globals.Logger.Verbose("Attempting to delete input file '" + file + "'"); Globals.Logger.Verbose("Attempting to delete input file '" + file + "'");
FileTools.SafeTryDeleteFile(file, true); FileTools.TryDeleteFile(file, true);
Globals.Logger.Verbose("File '" + file + "' deleted"); Globals.Logger.Verbose("File '" + file + "' deleted");
} }
catch (Exception ex) catch (Exception ex)
@@ -457,7 +457,7 @@ namespace SabreTools.Helper.Dats
} }
// Now delete the temp directory // Now delete the temp directory
FileTools.SafeTryDeleteDirectory(tempSubDir); FileTools.TryDeleteDirectory(tempSubDir);
} }
/// <summary> /// <summary>
@@ -764,7 +764,7 @@ namespace SabreTools.Helper.Dats
// And now clear the temp folder to get rid of any transient files if we unzipped // And now clear the temp folder to get rid of any transient files if we unzipped
if (isZip) if (isZip)
{ {
FileTools.SafeTryDeleteDirectory(tempDir); FileTools.TryDeleteDirectory(tempDir);
} }
return rebuilt; return rebuilt;

View File

@@ -11,8 +11,6 @@ using System.IO;
#else #else
using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Filesystem;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using SearchOption = System.IO.SearchOption; using SearchOption = System.IO.SearchOption;
using StreamWriter = System.IO.StreamWriter; using StreamWriter = System.IO.StreamWriter;
#endif #endif
@@ -512,7 +510,7 @@ Please check the log folder if the stats scrolled offscreen", false);
Path.Combine(outDir, reportName); Path.Combine(outDir, reportName);
// Create the StreamWriter for this file // Create the StreamWriter for this file
output.Add(StatDatFormat.None, new StreamWriter(File.Open(reportName, FileMode.Create, FileAccess.Write))); output.Add(StatDatFormat.None, new StreamWriter(FileTools.TryCreate(reportName)));
} }
if ((statDatFormat & StatDatFormat.CSV) != 0) if ((statDatFormat & StatDatFormat.CSV) != 0)
{ {
@@ -520,7 +518,7 @@ Please check the log folder if the stats scrolled offscreen", false);
Path.Combine(outDir, reportName); Path.Combine(outDir, reportName);
// Create the StreamWriter for this file // Create the StreamWriter for this file
output.Add(StatDatFormat.CSV, new StreamWriter(File.Open(reportName, FileMode.Create, FileAccess.Write))); output.Add(StatDatFormat.CSV, new StreamWriter(FileTools.TryCreate(reportName)));
} }
if ((statDatFormat & StatDatFormat.HTML) != 0) if ((statDatFormat & StatDatFormat.HTML) != 0)
{ {
@@ -528,7 +526,7 @@ Please check the log folder if the stats scrolled offscreen", false);
Path.Combine(outDir, reportName); Path.Combine(outDir, reportName);
// Create the StreamWriter for this file // Create the StreamWriter for this file
output.Add(StatDatFormat.HTML, new StreamWriter(File.Open(reportName, FileMode.Create, FileAccess.Write))); output.Add(StatDatFormat.HTML, new StreamWriter(FileTools.TryCreate(reportName)));
} }
if ((statDatFormat & StatDatFormat.TSV) != 0) if ((statDatFormat & StatDatFormat.TSV) != 0)
{ {
@@ -536,7 +534,7 @@ Please check the log folder if the stats scrolled offscreen", false);
Path.Combine(outDir, reportName); Path.Combine(outDir, reportName);
// Create the StreamWriter for this file // Create the StreamWriter for this file
output.Add(StatDatFormat.TSV, new StreamWriter(File.Open(reportName, FileMode.Create, FileAccess.Write))); output.Add(StatDatFormat.TSV, new StreamWriter(FileTools.TryCreate(reportName)));
} }
return output; return output;

View File

@@ -12,8 +12,6 @@ using Alphaleonis.Win32.Filesystem;
using BinaryReader = System.IO.BinaryReader; using BinaryReader = System.IO.BinaryReader;
using BinaryWriter = System.IO.BinaryWriter; using BinaryWriter = System.IO.BinaryWriter;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using IOException = System.IO.IOException; using IOException = System.IO.IOException;
using MemoryStream = System.IO.MemoryStream; using MemoryStream = System.IO.MemoryStream;
using PathTooLongException = System.IO.PathTooLongException; using PathTooLongException = System.IO.PathTooLongException;
@@ -428,7 +426,7 @@ namespace ROMVault2.SupportedFiles.Zip
} }
// Now try to open the file for reading // Now try to open the file for reading
_zipstream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _zipstream = FileTools.TryOpenRead(filename);
int read = _zipstream.Read(new byte[1], 0, 1); int read = _zipstream.Read(new byte[1], 0, 1);
if (read != 1) if (read != 1)
{ {
@@ -646,7 +644,7 @@ namespace ROMVault2.SupportedFiles.Zip
_zipFileInfo = new FileInfo(filename); _zipFileInfo = new FileInfo(filename);
// Now try to open the file // Now try to open the file
_zipstream = File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite); _zipstream = File.Open(filename, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
ZipOpen = ZipOpenType.OpenWrite; ZipOpen = ZipOpenType.OpenWrite;
return ZipReturn.ZipGood; return ZipReturn.ZipGood;
} }
@@ -759,7 +757,7 @@ namespace ROMVault2.SupportedFiles.Zip
_zipstream.Dispose(); _zipstream.Dispose();
// Delete the failed file // Delete the failed file
FileTools.SafeTryDeleteFile(_zipFileInfo.FullName); FileTools.TryDeleteFile(_zipFileInfo.FullName);
_zipFileInfo = null; _zipFileInfo = null;
_zipOpen = ZipOpenType.Closed; _zipOpen = ZipOpenType.Closed;
} }

View File

@@ -347,7 +347,7 @@ namespace SabreTools.Helper.Skippers
return new SkipperRule(); return new SkipperRule();
} }
return GetMatchingRule(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), skipperName); return GetMatchingRule(FileTools.TryOpenRead(input), skipperName);
} }
/// <summary> /// <summary>

View File

@@ -11,10 +11,6 @@ using Alphaleonis.Win32.Filesystem;
using BinaryReader = System.IO.BinaryReader; using BinaryReader = System.IO.BinaryReader;
using BinaryWriter = System.IO.BinaryWriter; using BinaryWriter = System.IO.BinaryWriter;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using FileShare = System.IO.FileShare;
using FileStream = System.IO.FileStream;
using SeekOrigin = System.IO.SeekOrigin; using SeekOrigin = System.IO.SeekOrigin;
using Stream = System.IO.Stream; using Stream = System.IO.Stream;
#endif #endif
@@ -54,12 +50,12 @@ namespace SabreTools.Helper.Skippers
} }
Globals.Logger.User("Attempting to apply rule to '" + input + "'"); Globals.Logger.User("Attempting to apply rule to '" + input + "'");
success = TransformStream(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), File.Open(output, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)); success = TransformStream(FileTools.TryOpenRead(input), FileTools.TryOpenWrite(output));
// If the output file has size 0, delete it // If the output file has size 0, delete it
if (new FileInfo(output).Length == 0) if (new FileInfo(output).Length == 0)
{ {
FileTools.SafeTryDeleteFile(output); FileTools.TryDeleteFile(output);
success = false; success = false;
} }

View File

@@ -14,11 +14,7 @@ using Alphaleonis.Win32.Filesystem;
using BinaryReader = System.IO.BinaryReader; using BinaryReader = System.IO.BinaryReader;
using BinaryWriter = System.IO.BinaryWriter; using BinaryWriter = System.IO.BinaryWriter;
using EndOfStreamException = System.IO.EndOfStreamException; using EndOfStreamException = System.IO.EndOfStreamException;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using FileShare = System.IO.FileShare;
using FileStream = System.IO.FileStream; using FileStream = System.IO.FileStream;
using MemoryStream = System.IO.MemoryStream;
using SeekOrigin = System.IO.SeekOrigin; using SeekOrigin = System.IO.SeekOrigin;
using Stream = System.IO.Stream; using Stream = System.IO.Stream;
#endif #endif
@@ -80,7 +76,7 @@ namespace SabreTools.Helper.Tools
Directory.CreateDirectory(outDir); Directory.CreateDirectory(outDir);
// Extract all files to the temp directory // Extract all files to the temp directory
SevenZipArchive sza = SevenZipArchive.Open(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); SevenZipArchive sza = SevenZipArchive.Open(FileTools.TryOpenRead(input));
foreach (SevenZipArchiveEntry entry in sza.Entries) foreach (SevenZipArchiveEntry entry in sza.Entries)
{ {
entry.WriteToDirectory(outDir, new ExtractionOptions{ PreserveFileTime = true, ExtractFullPath = true, Overwrite = true }); entry.WriteToDirectory(outDir, new ExtractionOptions{ PreserveFileTime = true, ExtractFullPath = true, Overwrite = true });
@@ -99,7 +95,7 @@ namespace SabreTools.Helper.Tools
// Decompress the input stream // Decompress the input stream
FileStream outstream = File.Create(Path.Combine(outDir, Path.GetFileNameWithoutExtension(input))); FileStream outstream = File.Create(Path.Combine(outDir, Path.GetFileNameWithoutExtension(input)));
GZipStream gzstream = new GZipStream(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Ionic.Zlib.CompressionMode.Decompress); GZipStream gzstream = new GZipStream(FileTools.TryOpenRead(input), Ionic.Zlib.CompressionMode.Decompress);
gzstream.CopyTo(outstream); gzstream.CopyTo(outstream);
// Dispose of the streams // Dispose of the streams
@@ -180,7 +176,7 @@ namespace SabreTools.Helper.Tools
continue; continue;
} }
FileStream writeStream = File.Open(Path.Combine(outDir, zf.Entries[i].FileName), FileMode.Open, FileAccess.Write, FileShare.ReadWrite); FileStream writeStream = FileTools.TryOpenWrite(Path.Combine(outDir, zf.Entries[i].FileName));
byte[] ibuffer = new byte[_bufferSize]; byte[] ibuffer = new byte[_bufferSize];
int ilen; int ilen;
@@ -268,7 +264,7 @@ namespace SabreTools.Helper.Tools
case ArchiveType.GZip: case ArchiveType.GZip:
// Decompress the input stream // Decompress the input stream
realEntry = Path.GetFileNameWithoutExtension(input); realEntry = Path.GetFileNameWithoutExtension(input);
GZipStream gzstream = new GZipStream(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Ionic.Zlib.CompressionMode.Decompress); GZipStream gzstream = new GZipStream(FileTools.TryOpenRead(input), Ionic.Zlib.CompressionMode.Decompress);
// Get the output path // Get the output path
realEntry = Path.Combine(Path.GetFullPath(tempDir), realEntry); realEntry = Path.Combine(Path.GetFullPath(tempDir), realEntry);
@@ -278,7 +274,7 @@ namespace SabreTools.Helper.Tools
} }
// Write the file out // Write the file out
FileStream gzfileout = File.Open(realEntry, FileMode.Create, FileAccess.Write); FileStream gzfileout = FileTools.TryCreate(realEntry);
byte[] gbuffer = new byte[_bufferSize]; byte[] gbuffer = new byte[_bufferSize];
int glen; int glen;
while ((glen = gzstream.Read(gbuffer, 0, _bufferSize)) > 0) while ((glen = gzstream.Read(gbuffer, 0, _bufferSize)) > 0)
@@ -367,7 +363,7 @@ namespace SabreTools.Helper.Tools
} }
// Write the file out // Write the file out
FileStream zipfileout = File.Open(realEntry, FileMode.Create, FileAccess.Write); FileStream zipfileout = FileTools.TryCreate(realEntry);
byte[] zbuffer = new byte[_bufferSize]; byte[] zbuffer = new byte[_bufferSize];
int zlen; int zlen;
while ((zlen = readStream.Read(zbuffer, 0, _bufferSize)) > 0) while ((zlen = readStream.Read(zbuffer, 0, _bufferSize)) > 0)
@@ -470,7 +466,7 @@ namespace SabreTools.Helper.Tools
break; break;
case ArchiveType.GZip:// Get the CRC and size from the file case ArchiveType.GZip:// Get the CRC and size from the file
BinaryReader br = new BinaryReader(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); BinaryReader br = new BinaryReader(FileTools.TryOpenRead(input));
br.BaseStream.Seek(-8, SeekOrigin.End); br.BaseStream.Seek(-8, SeekOrigin.End);
byte[] headercrc = br.ReadBytes(4); byte[] headercrc = br.ReadBytes(4);
crc = BitConverter.ToString(headercrc.Reverse().ToArray()).Replace("-", string.Empty).ToLowerInvariant(); crc = BitConverter.ToString(headercrc.Reverse().ToArray()).Replace("-", string.Empty).ToLowerInvariant();
@@ -617,7 +613,7 @@ namespace SabreTools.Helper.Tools
byte[] headermd5; // MD5 byte[] headermd5; // MD5
byte[] headercrc; // CRC byte[] headercrc; // CRC
ulong headersz; // Int64 size ulong headersz; // Int64 size
BinaryReader br = new BinaryReader(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); BinaryReader br = new BinaryReader(FileTools.TryOpenRead(input));
header = br.ReadBytes(12); header = br.ReadBytes(12);
headermd5 = br.ReadBytes(16); headermd5 = br.ReadBytes(16);
headercrc = br.ReadBytes(4); headercrc = br.ReadBytes(4);
@@ -696,7 +692,7 @@ namespace SabreTools.Helper.Tools
try try
{ {
byte[] magic = new byte[8]; byte[] magic = new byte[8];
BinaryReader br = new BinaryReader(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); BinaryReader br = new BinaryReader(FileTools.TryOpenRead(input));
magic = br.ReadBytes(8); magic = br.ReadBytes(8);
br.Dispose(); br.Dispose();
@@ -863,7 +859,7 @@ namespace SabreTools.Helper.Tools
return; return;
} }
BinaryReader br = new BinaryReader(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); BinaryReader br = new BinaryReader(FileTools.TryOpenRead(input));
// Check for the signature first (Skipping the SFX Module) // Check for the signature first (Skipping the SFX Module)
byte[] signature = br.ReadBytes(8); byte[] signature = br.ReadBytes(8);
@@ -1081,7 +1077,7 @@ namespace SabreTools.Helper.Tools
{ {
try try
{ {
Stream fread = File.Open(filename, FileMode.Open, FileAccess.Read); Stream fread = FileTools.TryOpenRead(filename);
uint ar, offs = 0; uint ar, offs = 0;
fread.Seek(0, SeekOrigin.Begin); fread.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[128]; byte[] buffer = new byte[128];
@@ -1290,7 +1286,7 @@ namespace SabreTools.Helper.Tools
// If the old file exists, delete it and replace // If the old file exists, delete it and replace
if (File.Exists(archiveFileName)) if (File.Exists(archiveFileName))
{ {
FileTools.SafeTryDeleteFile(archiveFileName); FileTools.TryDeleteFile(archiveFileName);
} }
File.Move(tempFile, archiveFileName); File.Move(tempFile, archiveFileName);
@@ -1402,14 +1398,14 @@ namespace SabreTools.Helper.Tools
} }
FileTools.CleanDirectory(tempPath); FileTools.CleanDirectory(tempPath);
FileTools.SafeTryDeleteDirectory(tempPath); FileTools.TryDeleteDirectory(tempPath);
} }
// Otherwise, sort the input files and write out in the correct order // Otherwise, sort the input files and write out in the correct order
else else
{ {
// Open the old archive for reading // Open the old archive for reading
Stream oldZipFileStream = File.Open(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream oldZipFileStream = FileTools.TryOpenRead(archiveFileName);
oldZipFile = new SevenZipExtractor(oldZipFileStream); oldZipFile = new SevenZipExtractor(oldZipFileStream);
// Map all inputs to index // Map all inputs to index
@@ -1444,7 +1440,7 @@ namespace SabreTools.Helper.Tools
ArchiveFormat = OutArchiveFormat.SevenZip, ArchiveFormat = OutArchiveFormat.SevenZip,
CompressionLevel = SevenZip.CompressionLevel.Normal, CompressionLevel = SevenZip.CompressionLevel.Normal,
}; };
Stream zipFileStream = File.Open(tempFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); Stream zipFileStream = FileTools.TryOpenWrite(tempFile);
// Get the order for the entries with the new file // Get the order for the entries with the new file
List<string> keys = inputIndexMap.Keys.ToList(); List<string> keys = inputIndexMap.Keys.ToList();
@@ -1465,12 +1461,12 @@ namespace SabreTools.Helper.Tools
// Otherwise, copy the file from the old archive // Otherwise, copy the file from the old archive
else else
{ {
Stream oldZipFileEntryStream = File.Open(inputFiles[index], FileMode.Create, FileAccess.ReadWrite, FileShare.None); Stream oldZipFileEntryStream = FileTools.TryOpenReadWrite(inputFiles[index]);
oldZipFile.ExtractFile(index, oldZipFileEntryStream); oldZipFile.ExtractFile(index, oldZipFileEntryStream);
zipFile.CompressFiles(zipFileStream, inputFiles[index]); zipFile.CompressFiles(zipFileStream, inputFiles[index]);
oldZipFileEntryStream.Dispose(); oldZipFileEntryStream.Dispose();
FileTools.SafeTryDeleteFile(inputFiles[index]); FileTools.TryDeleteFile(inputFiles[index]);
} }
} }
@@ -1489,19 +1485,19 @@ namespace SabreTools.Helper.Tools
// If the old file exists, delete it and replace // If the old file exists, delete it and replace
if (File.Exists(archiveFileName)) if (File.Exists(archiveFileName))
{ {
FileTools.SafeTryDeleteFile(archiveFileName); FileTools.TryDeleteFile(archiveFileName);
} }
File.Move(tempFile, archiveFileName); File.Move(tempFile, archiveFileName);
// Now make the file T7Z // Now make the file T7Z
// TODO: Add ACTUAL T7Z compatible code // TODO: Add ACTUAL T7Z compatible code
BinaryWriter bw = new BinaryWriter(File.Open(archiveFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); BinaryWriter bw = new BinaryWriter(FileTools.TryOpenReadWrite(archiveFileName));
bw.Seek(0, SeekOrigin.Begin); bw.Seek(0, SeekOrigin.Begin);
bw.Write(Constants.Torrent7ZipHeader); bw.Write(Constants.Torrent7ZipHeader);
bw.Seek(0, SeekOrigin.End); bw.Seek(0, SeekOrigin.End);
oldZipFile = new SevenZipExtractor(File.Open(archiveFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); oldZipFile = new SevenZipExtractor(FileTools.TryOpenReadWrite(archiveFileName));
// Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4) // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
byte[] tempsig = Constants.Torrent7ZipSignature; byte[] tempsig = Constants.Torrent7ZipSignature;
@@ -1572,8 +1568,8 @@ namespace SabreTools.Helper.Tools
if (!File.Exists(outfile)) if (!File.Exists(outfile))
{ {
// Compress the input stream // Compress the input stream
FileStream inputStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream inputStream = FileTools.TryOpenRead(input);
FileStream outputStream = File.Open(outfile, FileMode.Create, FileAccess.Write); FileStream outputStream = FileTools.TryCreate(outfile);
// Open the output file for writing // Open the output file for writing
BinaryWriter sw = new BinaryWriter(outputStream); BinaryWriter sw = new BinaryWriter(outputStream);
@@ -1777,14 +1773,14 @@ namespace SabreTools.Helper.Tools
} }
FileTools.CleanDirectory(tempPath); FileTools.CleanDirectory(tempPath);
FileTools.SafeTryDeleteDirectory(tempPath); FileTools.TryDeleteDirectory(tempPath);
} }
// Otherwise, sort the input files and write out in the correct order // Otherwise, sort the input files and write out in the correct order
else else
{ {
// Open the old archive for reading // Open the old archive for reading
Stream oldZipFileStream = File.Open(archiveFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream oldZipFileStream = FileTools.TryOpenRead(archiveFileName);
oldZipFile = new SevenZipExtractor(oldZipFileStream); oldZipFile = new SevenZipExtractor(oldZipFileStream);
// Map all inputs to index // Map all inputs to index
@@ -1819,7 +1815,7 @@ namespace SabreTools.Helper.Tools
ArchiveFormat = OutArchiveFormat.XZ, ArchiveFormat = OutArchiveFormat.XZ,
CompressionLevel = SevenZip.CompressionLevel.Normal, CompressionLevel = SevenZip.CompressionLevel.Normal,
}; };
Stream zipFileStream = File.Open(tempFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); Stream zipFileStream = FileTools.TryOpenWrite(tempFile);
// Get the order for the entries with the new file // Get the order for the entries with the new file
List<string> keys = inputIndexMap.Keys.ToList(); List<string> keys = inputIndexMap.Keys.ToList();
@@ -1840,12 +1836,12 @@ namespace SabreTools.Helper.Tools
// Otherwise, copy the file from the old archive // Otherwise, copy the file from the old archive
else else
{ {
Stream oldZipFileEntryStream = File.Open(inputFiles[index], FileMode.Create, FileAccess.ReadWrite, FileShare.None); Stream oldZipFileEntryStream = FileTools.TryCreate(inputFiles[index]);
oldZipFile.ExtractFile(index, oldZipFileEntryStream); oldZipFile.ExtractFile(index, oldZipFileEntryStream);
zipFile.CompressFiles(zipFileStream, inputFiles[index]); zipFile.CompressFiles(zipFileStream, inputFiles[index]);
oldZipFileEntryStream.Dispose(); oldZipFileEntryStream.Dispose();
FileTools.SafeTryDeleteFile(inputFiles[index]); FileTools.TryDeleteFile(inputFiles[index]);
} }
} }
@@ -1864,19 +1860,19 @@ namespace SabreTools.Helper.Tools
// If the old file exists, delete it and replace // If the old file exists, delete it and replace
if (File.Exists(archiveFileName)) if (File.Exists(archiveFileName))
{ {
FileTools.SafeTryDeleteFile(archiveFileName); FileTools.TryDeleteFile(archiveFileName);
} }
File.Move(tempFile, archiveFileName); File.Move(tempFile, archiveFileName);
// Now make the file TXZ // Now make the file TXZ
// TODO: Add ACTUAL TXZ compatible code (based on T7z) // TODO: Add ACTUAL TXZ compatible code (based on T7z)
BinaryWriter bw = new BinaryWriter(File.Open(archiveFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); BinaryWriter bw = new BinaryWriter(FileTools.TryOpenReadWrite(archiveFileName));
bw.Seek(0, SeekOrigin.Begin); bw.Seek(0, SeekOrigin.Begin);
bw.Write(Constants.Torrent7ZipHeader); bw.Write(Constants.Torrent7ZipHeader);
bw.Seek(0, SeekOrigin.End); bw.Seek(0, SeekOrigin.End);
oldZipFile = new SevenZipExtractor(File.Open(archiveFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)); oldZipFile = new SevenZipExtractor(FileTools.TryOpenReadWrite(archiveFileName));
// Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4) // Get the correct signature to use (Default 0, Unicode 1, SingleFile 2, StripFileNames 4)
byte[] tempsig = Constants.Torrent7ZipSignature; byte[] tempsig = Constants.Torrent7ZipSignature;
@@ -1986,7 +1982,7 @@ namespace SabreTools.Helper.Tools
int index = inputIndexMap[key]; int index = inputIndexMap[key];
// Open the input file for reading // Open the input file for reading
Stream freadStream = File.Open(inputFiles[index], FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream freadStream = FileTools.TryOpenRead(inputFiles[index]);
ulong istreamSize = (ulong)(new FileInfo(inputFiles[index]).Length); ulong istreamSize = (ulong)(new FileInfo(inputFiles[index]).Length);
DateTime dt = DateTime.Now; DateTime dt = DateTime.Now;
@@ -2063,7 +2059,7 @@ namespace SabreTools.Helper.Tools
if (index < 0) if (index < 0)
{ {
// Open the input file for reading // Open the input file for reading
Stream freadStream = File.Open(inputFiles[-index - 1], FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream freadStream = FileTools.TryOpenRead(inputFiles[-index - 1]);
ulong istreamSize = (ulong)(new FileInfo(inputFiles[-index - 1]).Length); ulong istreamSize = (ulong)(new FileInfo(inputFiles[-index - 1]).Length);
DateTime dt = DateTime.Now; DateTime dt = DateTime.Now;
@@ -2130,7 +2126,7 @@ namespace SabreTools.Helper.Tools
// If the old file exists, delete it and replace // If the old file exists, delete it and replace
if (File.Exists(archiveFileName)) if (File.Exists(archiveFileName))
{ {
FileTools.SafeTryDeleteFile(archiveFileName); FileTools.TryDeleteFile(archiveFileName);
} }
File.Move(tempFile, archiveFileName); File.Move(tempFile, archiveFileName);

View File

@@ -16,6 +16,9 @@ using Alphaleonis.Win32.Filesystem;
using BinaryReader = System.IO.BinaryReader; using BinaryReader = System.IO.BinaryReader;
using BinaryWriter = System.IO.BinaryWriter; using BinaryWriter = System.IO.BinaryWriter;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using FileShare = System.IO.FileShare;
using FileStream = System.IO.FileStream; using FileStream = System.IO.FileStream;
using IOException = System.IO.IOException; using IOException = System.IO.IOException;
using MemoryStream = System.IO.MemoryStream; using MemoryStream = System.IO.MemoryStream;
@@ -221,7 +224,7 @@ namespace SabreTools.Helper.Tools
{ {
// Create the input and output streams // Create the input and output streams
MemoryStream outputStream = new MemoryStream(); MemoryStream outputStream = new MemoryStream();
FileStream inputStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream inputStream = FileTools.TryOpenRead(input);
// Transform the stream and get the information from it // Transform the stream and get the information from it
rule.TransformStream(inputStream, outputStream, keepReadOpen: false, keepWriteOpen: true); rule.TransformStream(inputStream, outputStream, keepReadOpen: false, keepWriteOpen: true);
@@ -235,13 +238,13 @@ namespace SabreTools.Helper.Tools
else else
{ {
long length = new FileInfo(input).Length; long length = new FileInfo(input).Length;
rom = GetStreamInfo(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), length, omitFromScan, offset, false); rom = GetStreamInfo(TryOpenRead(input), length, omitFromScan, offset, false);
} }
} }
else else
{ {
long length = new FileInfo(input).Length; long length = new FileInfo(input).Length;
rom = GetStreamInfo(File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), length, omitFromScan, offset, false); rom = GetStreamInfo(TryOpenRead(input), length, omitFromScan, offset, false);
} }
// Add unique data from the file // Add unique data from the file
@@ -319,8 +322,8 @@ namespace SabreTools.Helper.Tools
return; return;
} }
FileStream fsr = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream fsr = TryOpenRead(input);
FileStream fsw = File.Open(output, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); FileStream fsw = TryOpenWrite(output);
AppendBytesToStream(fsr, fsw, bytesToAddToHead, bytesToAddToTail); AppendBytesToStream(fsr, fsw, bytesToAddToHead, bytesToAddToTail);
@@ -336,11 +339,11 @@ namespace SabreTools.Helper.Tools
{ {
foreach (string file in Directory.EnumerateFiles(dirname, "*", SearchOption.TopDirectoryOnly)) foreach (string file in Directory.EnumerateFiles(dirname, "*", SearchOption.TopDirectoryOnly))
{ {
SafeTryDeleteFile(file); TryDeleteFile(file);
} }
foreach (string dir in Directory.EnumerateDirectories(dirname, "*", SearchOption.TopDirectoryOnly)) foreach (string dir in Directory.EnumerateDirectories(dirname, "*", SearchOption.TopDirectoryOnly))
{ {
SafeTryDeleteDirectory(dir); TryDeleteDirectory(dir);
} }
} }
@@ -373,7 +376,7 @@ namespace SabreTools.Helper.Tools
// Get the header bytes from the file first // Get the header bytes from the file first
string hstr = string.Empty; string hstr = string.Empty;
BinaryReader br = new BinaryReader(File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); BinaryReader br = new BinaryReader(TryOpenRead(file));
// Extract the header as a string for the database // Extract the header as a string for the database
byte[] hbin = br.ReadBytes((int)rule.StartOffset); byte[] hbin = br.ReadBytes((int)rule.StartOffset);
@@ -520,13 +523,39 @@ namespace SabreTools.Helper.Tools
return true; return true;
} }
/// <summary>
/// Try to create a file for write, optionally throwing the error
/// </summary>
/// <param name="file">Name of the file to create</param>
/// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param>
/// <returns>An opened stream representing the file on success, null otherwise</returns>
public static FileStream TryCreate(string file, bool throwOnError = false)
{
// Now wrap opening the file
try
{
return File.Open(file, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
}
catch (Exception ex)
{
if (throwOnError)
{
throw ex;
}
else
{
return null;
}
}
}
/// <summary> /// <summary>
/// Try to safely delete a directory, optionally throwing the error /// Try to safely delete a directory, optionally throwing the error
/// </summary> /// </summary>
/// <param name="file">Name of the directory to delete</param> /// <param name="file">Name of the directory to delete</param>
/// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param> /// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param>
/// <returns>True if the file didn't exist or could be deleted, false otherwise</returns> /// <returns>True if the file didn't exist or could be deleted, false otherwise</returns>
public static bool SafeTryDeleteDirectory(string file, bool throwOnError = false) public static bool TryDeleteDirectory(string file, bool throwOnError = false)
{ {
// Check if the file exists first // Check if the file exists first
if (!Directory.Exists(file)) if (!Directory.Exists(file))
@@ -559,7 +588,7 @@ namespace SabreTools.Helper.Tools
/// <param name="file">Name of the file to delete</param> /// <param name="file">Name of the file to delete</param>
/// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param> /// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param>
/// <returns>True if the file didn't exist or could be deleted, false otherwise</returns> /// <returns>True if the file didn't exist or could be deleted, false otherwise</returns>
public static bool SafeTryDeleteFile(string file, bool throwOnError = false) public static bool TryDeleteFile(string file, bool throwOnError = false)
{ {
// Check if the file exists first // Check if the file exists first
if (!File.Exists(file)) if (!File.Exists(file))
@@ -586,6 +615,102 @@ namespace SabreTools.Helper.Tools
} }
} }
/// <summary>
/// Try to open a file for read, optionally throwing the error
/// </summary>
/// <param name="file">Name of the file to open</param>
/// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param>
/// <returns>An opened stream representing the file on success, null otherwise</returns>
public static FileStream TryOpenRead(string file, bool throwOnError = false)
{
// Check if the file exists first
if (!File.Exists(file))
{
return null;
}
// Now wrap opening the file
try
{
return File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
catch (Exception ex)
{
if (throwOnError)
{
throw ex;
}
else
{
return null;
}
}
}
/// <summary>
/// Try to open a file for read/write, optionally throwing the error
/// </summary>
/// <param name="file">Name of the file to open</param>
/// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param>
/// <returns>An opened stream representing the file on success, null otherwise</returns>
public static FileStream TryOpenReadWrite(string file, bool throwOnError = false)
{
// Check if the file exists first
if (!File.Exists(file))
{
return null;
}
// Now wrap opening the file
try
{
return File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
}
catch (Exception ex)
{
if (throwOnError)
{
throw ex;
}
else
{
return null;
}
}
}
/// <summary>
/// Try to open a file for write, optionally throwing the error
/// </summary>
/// <param name="file">Name of the file to open</param>
/// <param name="throwOnError">True if the error that is thrown should be thrown back to the caller, false otherwise</param>
/// <returns>An opened stream representing the file on success, null otherwise</returns>
public static FileStream TryOpenWrite(string file, bool throwOnError = false)
{
// Check if the file exists first
if (!File.Exists(file))
{
return null;
}
// Now wrap opening the file
try
{
return File.Open(file, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
}
catch (Exception ex)
{
if (throwOnError)
{
throw ex;
}
else
{
return null;
}
}
}
#endregion #endregion
#region Stream Information #region Stream Information

View File

@@ -14,8 +14,6 @@ using System.IO;
#else #else
using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Filesystem;
using FileAccess = System.IO.FileAccess;
using FileMode = System.IO.FileMode;
using FileStream = System.IO.FileStream; using FileStream = System.IO.FileStream;
#endif #endif
@@ -805,7 +803,7 @@ namespace SabreTools.Helper.Tools
{ {
// Read the BOM // Read the BOM
var bom = new byte[4]; var bom = new byte[4];
FileStream file = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream file = FileTools.TryOpenRead(filename);
file.Read(bom, 0, 4); file.Read(bom, 0, 4);
file.Dispose(); file.Dispose();
@@ -829,7 +827,7 @@ namespace SabreTools.Helper.Tools
var buffer = new byte[2048]; var buffer = new byte[2048];
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (var stream = FileTools.TryOpenRead(filePath))
stream.Read(buffer, 0, 2048); stream.Read(buffer, 0, 2048);
var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset); var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset);