[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,16 +101,17 @@ 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
byte[] hbin = br.ReadBytes(headerSize);
for (int i = 0; i < headerSize; i++)
{ {
// Extract the header as a string for the database hstr += BitConverter.ToString(new byte[] { hbin[i] });
byte[] hbin = br.ReadBytes(headerSize);
for (int i = 0; i < headerSize; 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,27 +488,32 @@ 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);
Skippers.TransformStream(input, output, rule, _logger, false, true);
Rom romNH = FileTools.GetSingleStreamInfo(output);
romNH.Name = "HEAD::" + rom.Name;
romNH.MachineName = rom.MachineName;
// Add the rom information to the Dat // Transform the stream and get the information from it
key = romNH.Size + "-" + romNH.CRC; Skippers.TransformStream(input, output, rule, _logger, false, true);
if (matchdat.Files.ContainsKey(key)) Rom romNH = FileTools.GetSingleStreamInfo(output);
{ romNH.Name = "HEAD::" + rom.Name;
matchdat.Files[key].Add(romNH); romNH.MachineName = rom.MachineName;
}
else // Add the rom information to the Dat
{ key = romNH.Size + "-" + romNH.CRC;
List<DatItem> temp = new List<DatItem>(); if (matchdat.Files.ContainsKey(key))
temp.Add(romNH); {
matchdat.Files.Add(key, temp); matchdat.Files[key].Add(romNH);
}
} }
else
{
List<DatItem> temp = new List<DatItem>();
temp.Add(romNH);
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,32 +83,34 @@ 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
for (int i = 0; i < inputFiles.Count; i++)
{ {
// Now loop through and add all files string inputFile = inputFiles[i];
for (int i = 0; i < inputFiles.Count; i++) Rom rom = roms[i];
// If the archive doesn't already contain the entry, add it
if (outarchive.GetEntry(rom.Name) == null)
{ {
string inputFile = inputFiles[i]; outarchive.CreateEntryFromFile(inputFile, rom.Name, CompressionLevel.Optimal);
Rom rom = roms[i]; }
// If the archive doesn't already contain the entry, add it // If there's a Date attached to the rom, change the entry to that Date
if (outarchive.GetEntry(rom.Name) == null) if (!string.IsNullOrEmpty(rom.Date))
{
DateTimeOffset dto = DateTimeOffset.Now;
if (DateTimeOffset.TryParse(rom.Date, out dto))
{ {
outarchive.CreateEntryFromFile(inputFile, rom.Name, CompressionLevel.Optimal); outarchive.GetEntry(rom.Name).LastWriteTime = dto;
}
// If there's a Date attached to the rom, change the entry to that Date
if (!string.IsNullOrEmpty(rom.Date))
{
DateTimeOffset dto = DateTimeOffset.Now;
if (DateTimeOffset.TryParse(rom.Date, out dto))
{
outarchive.GetEntry(rom.Name).LastWriteTime = dto;
}
} }
} }
} }
// Dispose of the streams
outarchive.Dispose();
success = true; success = true;
} }
catch (Exception ex) catch (Exception ex)
@@ -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);
zipReturn = zipFile.OpenWriteStream(false, true, rom.Name, streamSize, CompressionMethod.Deflated, out writeStream);
// Copy the input stream to the output ulong streamSize = (ulong)(new FileInfo(inputFile).Length);
byte[] buffer = new byte[8 * 1024]; zipReturn = zipFile.OpenWriteStream(false, true, rom.Name, streamSize, CompressionMethod.Deflated, out writeStream);
int len;
while ((len = readStream.Read(buffer, 0, buffer.Length)) > 0) // Copy the input stream to the output
{ byte[] buffer = new byte[8 * 1024];
writeStream.Write(buffer, 0, len); int len;
} while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
writeStream.Flush(); {
zipFile.CloseWriteStream(Convert.ToUInt32(rom.CRC, 16)); writeStream.Write(buffer, 0, len);
} }
writeStream.Flush();
zipFile.CloseWriteStream(Convert.ToUInt32(rom.CRC, 16));
//Dispose of the file stream
fs.Dispose();
} }
} }
@@ -368,48 +372,54 @@ 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));
// Write standard header and TGZ info
byte[] data = Constants.TorrentGZHeader
.Concat(Style.StringToByteArray(rom.MD5)) // MD5
.Concat(Style.StringToByteArray(rom.CRC)) // CRC
.Concat(BitConverter.GetBytes(rom.Size).Reverse().ToArray()) // Long size (Mirrored)
.ToArray();
sw.Write(data);
// Finally, copy the rest of the data from the original file
br.BaseStream.Seek(10, SeekOrigin.Begin);
int i = 10;
while (br.BaseStream.Position < br.BaseStream.Length)
{ {
using (BinaryReader br = new BinaryReader(File.OpenRead(outfile))) sw.Write(br.ReadByte());
{ i++;
// Write standard header and TGZ info
byte[] data = Constants.TorrentGZHeader
.Concat(Style.StringToByteArray(rom.MD5)) // MD5
.Concat(Style.StringToByteArray(rom.CRC)) // CRC
.Concat(BitConverter.GetBytes(rom.Size).Reverse().ToArray()) // Long size (Mirrored)
.ToArray();
sw.Write(data);
// Finally, copy the rest of the data from the original file
br.BaseStream.Seek(10, SeekOrigin.Begin);
int i = 10;
while (br.BaseStream.Position < br.BaseStream.Length)
{
sw.Write(br.ReadByte());
i++;
}
}
using (BinaryWriter bw = new BinaryWriter(File.Open(outfile, FileMode.Create)))
{
// Now write the new file over the original
sw.BaseStream.Seek(0, SeekOrigin.Begin);
bw.BaseStream.Seek(0, SeekOrigin.Begin);
sw.BaseStream.CopyTo(bw.BaseStream);
}
} }
// Dispose of the stream
br.Dispose();
// Now write the new file over the original
BinaryWriter bw = new BinaryWriter(File.Open(outfile, FileMode.Create));
sw.BaseStream.Seek(0, SeekOrigin.Begin);
bw.BaseStream.Seek(0, SeekOrigin.Begin);
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,27 +502,24 @@ 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);
// Create the temp directory
Directory.CreateDirectory(tempDir);
// Extract all files to the temp directory
SevenZipArchive sza = SevenZipArchive.Open(File.OpenRead(input));
foreach (IArchiveEntry iae in sza.Entries)
{ {
logger.Log("Found archive of type: " + at); iae.WriteToDirectory(tempDir, ExtractOptions.PreserveFileTime | ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
// Create the temp directory
Directory.CreateDirectory(tempDir);
// Extract all files to the temp directory
foreach (IArchiveEntry iae in sza.Entries)
{
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,37 +528,35 @@ 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);
// Create the temp directory
Directory.CreateDirectory(tempDir);
// Extract all files to the temp directory
IReader reader = ReaderFactory.Open(File.OpenRead(input));
bool succeeded = reader.MoveToNextEntry();
while (succeeded)
{ {
logger.Log("Found archive of type: " + at); reader.WriteEntryToDirectory(tempDir, ExtractOptions.PreserveFileTime | ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
succeeded = reader.MoveToNextEntry();
if ((at == ArchiveType.Zip && zip != ArchiveScanLevel.External) ||
(at == ArchiveType.Rar && rar != ArchiveScanLevel.External))
{
// Create the temp directory
Directory.CreateDirectory(tempDir);
// Extract all files to the temp directory
bool succeeded = reader.MoveToNextEntry();
while (succeeded)
{
reader.WriteEntryToDirectory(tempDir, ExtractOptions.PreserveFileTime | ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
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);
gzstream.CopyTo(outstream);
outfile = Path.GetFullPath(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)));
using(FileStream itemstream = File.OpenRead(input)) // Dispose of the streams
{ outstream.Dispose();
using (FileStream outstream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)))) gzstream.Dispose();
{
using (GZipStream gzstream = new GZipStream(itemstream, CompressionMode.Decompress))
{
gzstream.CopyTo(outstream);
outfile = Path.GetFullPath(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(input)));
}
}
}
} }
} }
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,15 +1060,13 @@ 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,29 +1089,31 @@ 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;
long adjustedLength = br.BaseStream.Length - bytesToRemoveFromTail;
// Seek to the correct position
br.BaseStream.Seek((bytesToRemoveFromHead < 0 ? 0 : bytesToRemoveFromHead), SeekOrigin.Begin);
// Now read the file in chunks and write out
byte[] buffer = new byte[bufferSize];
while (br.BaseStream.Position <= (adjustedLength - bufferSize))
{ {
int bufferSize = 1024; buffer = br.ReadBytes(bufferSize);
long adjustedLength = br.BaseStream.Length - bytesToRemoveFromTail;
// Seek to the correct position
br.BaseStream.Seek((bytesToRemoveFromHead < 0 ? 0 : bytesToRemoveFromHead), SeekOrigin.Begin);
// Now read the file in chunks and write out
byte[] buffer = new byte[bufferSize];
while (br.BaseStream.Position <= (adjustedLength - bufferSize))
{
buffer = br.ReadBytes(bufferSize);
bw.Write(buffer);
}
// For the final chunk, if any, write out only that number of bytes
int length = (int)(adjustedLength - br.BaseStream.Position);
buffer = new byte[length];
buffer = br.ReadBytes(length);
bw.Write(buffer); bw.Write(buffer);
} }
// For the final chunk, if any, write out only that number of bytes
int length = (int)(adjustedLength - br.BaseStream.Position);
buffer = new byte[length];
buffer = br.ReadBytes(length);
bw.Write(buffer);
br.Dispose();
bw.Dispose();
} }
/// <summary> /// <summary>
@@ -1165,35 +1155,37 @@ 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);
}
int bufferSize = 1024;
// Now read the file in chunks and write out
byte[] buffer = new byte[bufferSize];
while (br.BaseStream.Position <= (br.BaseStream.Length - bufferSize))
{
buffer = br.ReadBytes(bufferSize);
bw.Write(buffer);
}
// For the final chunk, if any, write out only that number of bytes
int length = (int)(br.BaseStream.Length - br.BaseStream.Position);
buffer = new byte[length];
buffer = br.ReadBytes(length);
bw.Write(buffer);
if (bytesToAddToTail.Count() > 0)
{
bw.Write(bytesToAddToTail);
}
} }
int bufferSize = 1024;
// Now read the file in chunks and write out
byte[] buffer = new byte[bufferSize];
while (br.BaseStream.Position <= (br.BaseStream.Length - bufferSize))
{
buffer = br.ReadBytes(bufferSize);
bw.Write(buffer);
}
// For the final chunk, if any, write out only that number of bytes
int length = (int)(br.BaseStream.Length - br.BaseStream.Position);
buffer = new byte[length];
buffer = br.ReadBytes(length);
bw.Write(buffer);
if (bytesToAddToTail.Count() > 0)
{
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;