[ALL] Stop using "using" for everything except databases

This commit is contained in:
Matt Nadareski
2016-09-22 15:36:02 -07:00
parent 6b43053b7d
commit 74fbe60686
6 changed files with 239 additions and 248 deletions

View File

@@ -499,7 +499,6 @@ namespace SabreTools.Helper
{ {
StreamReader sr = File.OpenText(filename); StreamReader sr = File.OpenText(filename);
string first = sr.ReadLine(); string first = sr.ReadLine();
sr.Close();
sr.Dispose(); sr.Dispose();
if (first.Contains("<") && first.Contains(">")) if (first.Contains("<") && first.Contains(">"))
{ {
@@ -1289,7 +1288,6 @@ namespace SabreTools.Helper
} }
} }
sr.Close();
sr.Dispose(); sr.Dispose();
} }
@@ -1454,7 +1452,6 @@ namespace SabreTools.Helper
} }
} }
sr.Close();
sr.Dispose(); sr.Dispose();
} }
@@ -2218,7 +2215,6 @@ namespace SabreTools.Helper
} }
} }
xtr.Close();
xtr.Dispose(); xtr.Dispose();
} }
} }
@@ -3215,8 +3211,8 @@ namespace SabreTools.Helper
WriteFooter(sw, outputFormat, datdata, depth, logger); WriteFooter(sw, outputFormat, datdata, depth, logger);
logger.Log("File written!" + Environment.NewLine); logger.Log("File written!" + Environment.NewLine);
sw.Close(); sw.Dispose();
fs.Close(); fs.Dispose();
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -101,15 +101,16 @@ namespace SabreTools
// Now take care of the header and new output file // Now take care of the header and new output file
string hstr = string.Empty; string hstr = string.Empty;
using (BinaryReader br = new BinaryReader(File.OpenRead(file))) BinaryReader br = new BinaryReader(File.OpenRead(file));
{
// Extract the header as a string for the database // Extract the header as a string for the database
byte[] hbin = br.ReadBytes(headerSize); byte[] hbin = br.ReadBytes(headerSize);
for (int i = 0; i < headerSize; i++) for (int i = 0; i < headerSize; i++)
{ {
hstr += BitConverter.ToString(new byte[] { hbin[i] }); hstr += BitConverter.ToString(new byte[] { hbin[i] });
} }
}
br.Dispose();
// Then find an apply the exact rule to the file // Then find an apply the exact rule to the file
SkipperRule rule = Skippers.MatchesSkipper(file, "", _logger); SkipperRule rule = Skippers.MatchesSkipper(file, "", _logger);

View File

@@ -488,9 +488,11 @@ namespace SabreTools.Helper
// If there's a match, get the new information from the stream // If there's a match, get the new information from the stream
if (rule.Tests != null && rule.Tests.Count != 0) if (rule.Tests != null && rule.Tests.Count != 0)
{ {
using (MemoryStream output = new MemoryStream()) // Create the input and output streams
{ MemoryStream output = new MemoryStream();
FileStream input = File.OpenRead(file); FileStream input = File.OpenRead(file);
// Transform the stream and get the information from it
Skippers.TransformStream(input, output, rule, _logger, false, true); Skippers.TransformStream(input, output, rule, _logger, false, true);
Rom romNH = FileTools.GetSingleStreamInfo(output); Rom romNH = FileTools.GetSingleStreamInfo(output);
romNH.Name = "HEAD::" + rom.Name; romNH.Name = "HEAD::" + rom.Name;
@@ -508,7 +510,10 @@ namespace SabreTools.Helper
temp.Add(romNH); temp.Add(romNH);
matchdat.Files.Add(key, temp); matchdat.Files.Add(key, temp);
} }
}
// Dispose of the streams
output.Dispose();
input.Dispose();
} }
return true; return true;
@@ -1096,12 +1101,14 @@ namespace SabreTools.Helper
} }
// Write out the value to each of the romba depot files // Write out the value to each of the romba depot files
using (StreamWriter tw = new StreamWriter(File.Open(Path.Combine(_outDir, ".romba_size"), FileMode.Create, FileAccess.Write))) StreamWriter tw = new StreamWriter(File.Open(Path.Combine(_outDir, ".romba_size"), FileMode.Create, FileAccess.Write));
using (StreamWriter twb = new StreamWriter(File.Open(Path.Combine(_outDir, ".romba_size.backup"), FileMode.Create, FileAccess.Write))) StreamWriter twb = new StreamWriter(File.Open(Path.Combine(_outDir, ".romba_size.backup"), FileMode.Create, FileAccess.Write));
{
tw.Write(size); tw.Write(size);
twb.Write(size); twb.Write(size);
}
tw.Dispose();
twb.Dispose();
} }
return success; return success;

View File

@@ -480,7 +480,6 @@ namespace SabreTools.Helper
// If we're not keeping the stream open, dispose of the binary reader // If we're not keeping the stream open, dispose of the binary reader
if (!keepOpen) if (!keepOpen)
{ {
input.Close();
input.Dispose(); input.Dispose();
} }
@@ -494,7 +493,6 @@ namespace SabreTools.Helper
// If we're not keeping the stream open, dispose of the binary reader // If we're not keeping the stream open, dispose of the binary reader
if (!keepOpen) if (!keepOpen)
{ {
input.Close();
input.Dispose(); input.Dispose();
} }
@@ -677,14 +675,12 @@ namespace SabreTools.Helper
// If we're not keeping the read stream open, dispose of the binary reader // If we're not keeping the read stream open, dispose of the binary reader
if (!keepReadOpen) if (!keepReadOpen)
{ {
br?.Close();
br?.Dispose(); br?.Dispose();
} }
// If we're not keeping the write stream open, dispose of the binary reader // If we're not keeping the write stream open, dispose of the binary reader
if (!keepWriteOpen) if (!keepWriteOpen)
{ {
bw?.Close();
bw?.Dispose(); bw?.Dispose();
} }
} }

View File

@@ -83,8 +83,8 @@ namespace SabreTools.Helper
} }
// Open the archive for writing // Open the archive for writing
using (outarchive = System.IO.Compression.ZipFile.Open(archiveFileName, ZipArchiveMode.Update)) outarchive = System.IO.Compression.ZipFile.Open(archiveFileName, ZipArchiveMode.Update);
{
// Now loop through and add all files // Now loop through and add all files
for (int i = 0; i < inputFiles.Count; i++) for (int i = 0; i < inputFiles.Count; i++)
{ {
@@ -107,7 +107,9 @@ namespace SabreTools.Helper
} }
} }
} }
}
// Dispose of the streams
outarchive.Dispose();
success = true; success = true;
} }
@@ -211,21 +213,23 @@ namespace SabreTools.Helper
Rom rom = roms[inputIndexMap[key]]; Rom rom = roms[inputIndexMap[key]];
// Open the input file for reading // Open the input file for reading
using (Stream readStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) Stream fs = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
{
ulong streamSize = (ulong)(new FileInfo(inputFile).Length); ulong streamSize = (ulong)(new FileInfo(inputFile).Length);
zipReturn = zipFile.OpenWriteStream(false, true, rom.Name, streamSize, CompressionMethod.Deflated, out writeStream); zipReturn = zipFile.OpenWriteStream(false, true, rom.Name, streamSize, CompressionMethod.Deflated, out writeStream);
// Copy the input stream to the output // Copy the input stream to the output
byte[] buffer = new byte[8 * 1024]; byte[] buffer = new byte[8 * 1024];
int len; int len;
while ((len = readStream.Read(buffer, 0, buffer.Length)) > 0) while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
{ {
writeStream.Write(buffer, 0, len); writeStream.Write(buffer, 0, len);
} }
writeStream.Flush(); writeStream.Flush();
zipFile.CloseWriteStream(Convert.ToUInt32(rom.CRC, 16)); zipFile.CloseWriteStream(Convert.ToUInt32(rom.CRC, 16));
}
//Dispose of the file stream
fs.Dispose();
} }
} }
@@ -368,21 +372,24 @@ namespace SabreTools.Helper
outDir = Path.GetFullPath(outDir); outDir = Path.GetFullPath(outDir);
// Now get the Rom info for the file so we have hashes and size // Now get the Rom info for the file so we have hashes and size
Rom rom = FileTools.GetSingleFileInfo(input); Rom rom = GetSingleFileInfo(input);
// If it doesn't exist, create the output file and then write // If it doesn't exist, create the output file and then write
string outfile = Path.Combine(outDir, rom.SHA1 + ".gz"); string outfile = Path.Combine(outDir, rom.SHA1 + ".gz");
using (FileStream inputstream = new FileStream(input, FileMode.Open))
using (GZipStream output = new GZipStream(File.Open(outfile, FileMode.Create, FileAccess.Write), CompressionMode.Compress)) // Compress the input stream
{ FileStream inputStream = File.OpenRead(input);
inputstream.CopyTo(output); GZipStream outputStream = new GZipStream(File.Open(outfile, FileMode.Create, FileAccess.Write), CompressionMode.Compress);
} inputStream.CopyTo(outputStream);
// Dispose of the streams
inputStream.Dispose();
outputStream.Dispose();
// Now that it's ready, inject the header info // Now that it's ready, inject the header info
using (BinaryWriter sw = new BinaryWriter(new MemoryStream())) BinaryWriter sw = new BinaryWriter(new MemoryStream());
{ BinaryReader br = new BinaryReader(File.OpenRead(outfile));
using (BinaryReader br = new BinaryReader(File.OpenRead(outfile)))
{
// Write standard header and TGZ info // Write standard header and TGZ info
byte[] data = Constants.TorrentGZHeader byte[] data = Constants.TorrentGZHeader
.Concat(Style.StringToByteArray(rom.MD5)) // MD5 .Concat(Style.StringToByteArray(rom.MD5)) // MD5
@@ -399,16 +406,19 @@ namespace SabreTools.Helper
sw.Write(br.ReadByte()); sw.Write(br.ReadByte());
i++; i++;
} }
}
using (BinaryWriter bw = new BinaryWriter(File.Open(outfile, FileMode.Create))) // Dispose of the stream
{ br.Dispose();
// Now write the new file over the original // Now write the new file over the original
BinaryWriter bw = new BinaryWriter(File.Open(outfile, FileMode.Create));
sw.BaseStream.Seek(0, SeekOrigin.Begin); sw.BaseStream.Seek(0, SeekOrigin.Begin);
bw.BaseStream.Seek(0, SeekOrigin.Begin); bw.BaseStream.Seek(0, SeekOrigin.Begin);
sw.BaseStream.CopyTo(bw.BaseStream); sw.BaseStream.CopyTo(bw.BaseStream);
}
} // Dispose of the streams
bw.Dispose();
sw.Dispose();
// If we're in romba mode, create the subfolder and move the file // If we're in romba mode, create the subfolder and move the file
if (romba) if (romba)
@@ -492,14 +502,9 @@ namespace SabreTools.Helper
return encounteredErrors; return encounteredErrors;
} }
FileStream fs = null;
try try
{ {
fs = File.OpenRead(input);
if (at == ArchiveType.SevenZip && sevenzip != ArchiveScanLevel.External) if (at == ArchiveType.SevenZip && sevenzip != ArchiveScanLevel.External)
{
using (SevenZipArchive sza = SevenZipArchive.Open(fs))
{ {
logger.Log("Found archive of type: " + at); logger.Log("Found archive of type: " + at);
@@ -507,12 +512,14 @@ namespace SabreTools.Helper
Directory.CreateDirectory(tempDir); Directory.CreateDirectory(tempDir);
// Extract all files to the temp directory // Extract all files to the temp directory
SevenZipArchive sza = SevenZipArchive.Open(File.OpenRead(input));
foreach (IArchiveEntry iae in sza.Entries) foreach (IArchiveEntry iae in sza.Entries)
{ {
iae.WriteToDirectory(tempDir, ExtractOptions.PreserveFileTime | ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite); iae.WriteToDirectory(tempDir, ExtractOptions.PreserveFileTime | ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
} }
encounteredErrors = false; encounteredErrors = false;
} sza.Dispose();
} }
else if (at == ArchiveType.GZip && gz != ArchiveScanLevel.External) else if (at == ArchiveType.GZip && gz != ArchiveScanLevel.External)
{ {
@@ -521,28 +528,27 @@ namespace SabreTools.Helper
// Create the temp directory // Create the temp directory
Directory.CreateDirectory(tempDir); Directory.CreateDirectory(tempDir);
using (FileStream outstream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)))) // Decompress the input stream
{ FileStream outstream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)));
using (GZipStream gzstream = new GZipStream(fs, CompressionMode.Decompress)) GZipStream gzstream = new GZipStream(File.OpenRead(input), CompressionMode.Decompress);
{
gzstream.CopyTo(outstream); gzstream.CopyTo(outstream);
}
} // Dispose of the streams
outstream.Dispose();
gzstream.Dispose();
encounteredErrors = false; encounteredErrors = false;
} }
else else if ((at == ArchiveType.Zip && zip != ArchiveScanLevel.External)
{ || (at == ArchiveType.Rar && rar != ArchiveScanLevel.External))
using (IReader reader = ReaderFactory.Open(fs))
{ {
logger.Log("Found archive of type: " + at); logger.Log("Found archive of type: " + at);
if ((at == ArchiveType.Zip && zip != ArchiveScanLevel.External) ||
(at == ArchiveType.Rar && rar != ArchiveScanLevel.External))
{
// Create the temp directory // Create the temp directory
Directory.CreateDirectory(tempDir); Directory.CreateDirectory(tempDir);
// Extract all files to the temp directory // Extract all files to the temp directory
IReader reader = ReaderFactory.Open(File.OpenRead(input));
bool succeeded = reader.MoveToNextEntry(); bool succeeded = reader.MoveToNextEntry();
while (succeeded) while (succeeded)
{ {
@@ -550,8 +556,7 @@ namespace SabreTools.Helper
succeeded = reader.MoveToNextEntry(); succeeded = reader.MoveToNextEntry();
} }
encounteredErrors = false; encounteredErrors = false;
} reader.Dispose();
}
} }
} }
catch (EndOfStreamException) catch (EndOfStreamException)
@@ -567,11 +572,6 @@ namespace SabreTools.Helper
// Don't log file open errors // Don't log file open errors
encounteredErrors = true; encounteredErrors = true;
} }
finally
{
fs?.Close();
fs?.Dispose();
}
return encounteredErrors; return encounteredErrors;
} }
@@ -601,13 +601,12 @@ namespace SabreTools.Helper
IReader reader = null; IReader reader = null;
try try
{ {
reader = ReaderFactory.Open(File.OpenRead(input));
if (at == ArchiveType.Zip || at == ArchiveType.SevenZip || at == ArchiveType.Rar) if (at == ArchiveType.Zip || at == ArchiveType.SevenZip || at == ArchiveType.Rar)
{ {
// Create the temp directory // Create the temp directory
Directory.CreateDirectory(tempDir); Directory.CreateDirectory(tempDir);
reader = ReaderFactory.Open(File.OpenRead(input));
while (reader.MoveToNextEntry()) while (reader.MoveToNextEntry())
{ {
logger.Log("Current entry name: '" + reader.Entry.Key + "'"); logger.Log("Current entry name: '" + reader.Entry.Key + "'");
@@ -624,20 +623,15 @@ namespace SabreTools.Helper
} }
else if (at == ArchiveType.GZip) else if (at == ArchiveType.GZip)
{ {
// Dispose the original reader // Decompress the input stream
reader.Dispose(); FileStream outstream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)));
GZipStream gzstream = new GZipStream(File.OpenRead(input), CompressionMode.Decompress);
using(FileStream itemstream = File.OpenRead(input))
{
using (FileStream outstream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input))))
{
using (GZipStream gzstream = new GZipStream(itemstream, CompressionMode.Decompress))
{
gzstream.CopyTo(outstream); gzstream.CopyTo(outstream);
outfile = Path.GetFullPath(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input))); outfile = Path.GetFullPath(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)));
}
} // Dispose of the streams
} outstream.Dispose();
gzstream.Dispose();
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -831,20 +825,18 @@ namespace SabreTools.Helper
if (at == ArchiveType.GZip) if (at == ArchiveType.GZip)
{ {
// Get the CRC and size from the file // Get the CRC and size from the file
using (BinaryReader br = new BinaryReader(File.OpenRead(input))) BinaryReader br = new BinaryReader(File.OpenRead(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();
byte[] headersize = br.ReadBytes(4); byte[] headersize = br.ReadBytes(4);
size = BitConverter.ToInt32(headersize.Reverse().ToArray(), 0); size = BitConverter.ToInt32(headersize.Reverse().ToArray(), 0);
br.Dispose();
} }
}
reader = ReaderFactory.Open(File.OpenRead(input));
if (at != ArchiveType.Tar) if (at != ArchiveType.Tar)
{ {
reader = ReaderFactory.Open(File.OpenRead(input));
while (reader.MoveToNextEntry()) while (reader.MoveToNextEntry())
{ {
if (reader.Entry != null && !reader.Entry.IsDirectory) if (reader.Entry != null && !reader.Entry.IsDirectory)
@@ -907,13 +899,12 @@ namespace SabreTools.Helper
byte[] headermd5; // MD5 byte[] headermd5; // MD5
byte[] headercrc; // CRC byte[] headercrc; // CRC
byte[] headersz; // Int64 size byte[] headersz; // Int64 size
using (BinaryReader br = new BinaryReader(File.OpenRead(input))) BinaryReader br = new BinaryReader(File.OpenRead(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);
headersz = br.ReadBytes(8); headersz = br.ReadBytes(8);
} br.Dispose();
// If the header is not correct, return a blank rom // If the header is not correct, return a blank rom
bool correct = true; bool correct = true;
@@ -978,10 +969,9 @@ namespace SabreTools.Helper
try try
{ {
byte[] magic = new byte[8]; byte[] magic = new byte[8];
using (BinaryReader br = new BinaryReader(File.OpenRead(input))) BinaryReader br = new BinaryReader(File.OpenRead(input));
{
magic = br.ReadBytes(8); magic = br.ReadBytes(8);
} br.Dispose();
// Convert it to an uppercase string // Convert it to an uppercase string
string mstr = string.Empty; string mstr = string.Empty;
@@ -1070,16 +1060,14 @@ namespace SabreTools.Helper
/// <param name="input">Name of the input file to check</param> /// <param name="input">Name of the input file to check</param>
/// <param name="logger">Logger object for file and console output</param> /// <param name="logger">Logger object for file and console output</param>
/// <remarks>http://cpansearch.perl.org/src/BJOERN/Compress-Deflate7-1.0/7zip/DOC/7zFormat.txt</remarks> /// <remarks>http://cpansearch.perl.org/src/BJOERN/Compress-Deflate7-1.0/7zip/DOC/7zFormat.txt</remarks>
public static void GetSevenZipFIleInfo(string input, Logger logger) public static void GetSevenZipFileInfo(string input, Logger logger)
{
using (BinaryReader br = new BinaryReader(File.OpenRead(input)))
{ {
BinaryReader br = new BinaryReader(File.OpenRead(input));
br.ReadBytes(6); // BYTE kSignature[6] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}; br.ReadBytes(6); // BYTE kSignature[6] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};
logger.User("ArchiveVersion (Major.Minor): " + br.ReadByte() + "." + br.ReadByte()); logger.User("ArchiveVersion (Major.Minor): " + br.ReadByte() + "." + br.ReadByte());
logger.User("StartHeaderCRC: " + br.ReadUInt32()); logger.User("StartHeaderCRC: " + br.ReadUInt32());
logger.User("StartHeader (NextHeaderOffset, NextHeaderSize, NextHeaderCRC)" + br.ReadUInt64() + ", " + br.ReadUInt64() + ", " + br.ReadUInt32()); logger.User("StartHeader (NextHeaderOffset, NextHeaderSize, NextHeaderCRC)" + br.ReadUInt64() + ", " + br.ReadUInt64() + ", " + br.ReadUInt32());
} }
}
#endregion #endregion
@@ -1101,9 +1089,9 @@ namespace SabreTools.Helper
} }
// Read the input file and write to the fail // Read the input file and write to the fail
using (BinaryReader br = new BinaryReader(File.OpenRead(input))) BinaryReader br = new BinaryReader(File.OpenRead(input));
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(output))) BinaryWriter bw = new BinaryWriter(File.OpenWrite(output));
{
int bufferSize = 1024; int bufferSize = 1024;
long adjustedLength = br.BaseStream.Length - bytesToRemoveFromTail; long adjustedLength = br.BaseStream.Length - bytesToRemoveFromTail;
@@ -1123,7 +1111,9 @@ namespace SabreTools.Helper
buffer = new byte[length]; buffer = new byte[length];
buffer = br.ReadBytes(length); buffer = br.ReadBytes(length);
bw.Write(buffer); bw.Write(buffer);
}
br.Dispose();
bw.Dispose();
} }
/// <summary> /// <summary>
@@ -1165,9 +1155,9 @@ namespace SabreTools.Helper
return; return;
} }
using (BinaryReader br = new BinaryReader(File.OpenRead(input))) BinaryReader br = new BinaryReader(File.OpenRead(input));
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(output))) BinaryWriter bw = new BinaryWriter(File.OpenWrite(output));
{
if (bytesToAddToHead.Count() > 0) if (bytesToAddToHead.Count() > 0)
{ {
bw.Write(bytesToAddToHead); bw.Write(bytesToAddToHead);
@@ -1193,7 +1183,9 @@ namespace SabreTools.Helper
{ {
bw.Write(bytesToAddToTail); bw.Write(bytesToAddToTail);
} }
}
br.Dispose();
bw.Dispose();
} }
/// <summary> /// <summary>

View File

@@ -610,10 +610,9 @@ namespace SabreTools.Helper
{ {
// Read the BOM // Read the BOM
var bom = new byte[4]; var bom = new byte[4];
using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read)) FileStream file = File.OpenRead(filename);
{
file.Read(bom, 0, 4); file.Read(bom, 0, 4);
} file.Dispose();
// Analyze the BOM // Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7; if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;