Reputation: 428
Im facing an difficulty while trying to split a file by hex address to hex address. Its seems as though its splitting fine, but when i check the file, its always copying every byte from the start of the file not the start address.
Please let me know where i am going wrong input string is hex address(string) converted to a long
private void HexSplit(string inputFile, string outputFile, string startAddress, string endAddress)
{
FileStream hexReader = new FileStream(inputFile, FileMode.Open);
FileStream hexWriter = new FileStream(outputFile, FileMode.Create);
long StartAddress = Convert.ToInt64(startAddress.ToUpper(), 16);
long EndAddress = Convert.ToInt64(endAddress.ToUpper(), 16);
int bytecount = 0;
while (bytecount != EndAddress)
{
if (bytecount >= StartAddress && bytecount <= EndAddress) hexWriter.WriteByte((byte)hexReader.ReadByte());
bytecount++;
}
hexReader.Close();
hexReader.Dispose();
hexWriter.Close();
hexWriter.Dispose();
}
Upvotes: 1
Views: 388
Reputation: 216302
You should read the input to have the reader positioned on the current starting point
byte b = hexReader.ReadByte();
if (bytecount >= StartAddress && bytecount <= EndAddress)
hexWriter.WriteByte(b);
bytecount++;
or you can use the Filestream.Position property to directly set the correct starting point avoiding to read unnecessary parts of the input file
long byteCount = StartAddress;
hexReader.Position = StartAddress;
while (bytecount <= EndAddress)
{
hexWriter.WriteByte((byte)hexReader.ReadByte());
bytecount++;
}
Notice that in both cases you should check for the input passed because if the addresses are bigger than the length of the file you will receive an exception
if(hexReader.Length < EndAddress)
// Error message and return
Upvotes: 1