Hey guys, I'm new to C# and I'm working on a little project for my C# class. I've got a form that opens a file using the openfile dialog, however, I'm supposed to have it read the first 10 bytes and the last 10 bytes of a file and convert it to hex and write the output to a text box. What's the best way to achieve this? I've got 75% of my project completed already but I'm stuck on this litte snippet of code. I'd appreciate any help or if you can point me to another forum or article, that would be great.
from Austin TX.
AJPosted May 7, 2008, 1:53 AM
Thank you Brandon. That worked like a charm. I would have never thought to use the StringBuilder class (since I'm still a beginner), but that and the arrays were the missing ingredients. You rock!
Posted May 3, 2008, 8:39 PM
FileStream fileStream = new FileStream("MyTextFile.txt", FileMode.Open, FileAccess.Read);
(You may wanna put a length check in there just to make sure that the file stream contains at least 10 characters using if(fileStream.Length > 10))
Then, you will need to create two byte arrays large enough to hold ten characters each:
byte[] startDataArray = new byte[10];
byte[] endDataArray = new byte[10];
Then, read data from the file into the arrays using the file streams Read() method:
//This will read the contents from the beginning of the stream
//to the 10th index and store it in the startDataArray
fileStream.Read(startDataArray, 0, 10);
//Move to the 10th index from the end of the stream
//using the Seek() method.
fileStream.Seek(fileStream.Length - 10, SeekOrigin.Begin);
fileStream.Read(endDataArray, 0, 10);
Next, you will need to concatenate the arrays, and add them to a StringBuilder, converting each byte to its hex equivelent as you iterate through them. I write a method to do this:
private string ConvertByteArraysToHex(byte[] arrayOne, byte[] arrayTwo)
{
//When you make alot of iterations or need to
//concatenate alot of strings, use a StringBuilder.
//It work much better
StringBuilder contentsBuilder = new StringBuilder(arrayOne.Length + arrayTwo.Length);
//Iterate through array one and add its contents.
for (int i = 0; i < arrayOne.Length; i++)
{
//Convert it to hex, then add it to the builder.
contentsBuilder.Append(arrayOne[i].ToString("X") + "-");
}
//Iterate through array two and add its contents.
for (int i = 0; i < arrayTwo.Length; i++)
{
//I delimited each "nibble" using
//dashes for easier reading
contentsBuilder.Append(arrayTwo[i].ToString("X") + "-");
}
return contentsBuilder.ToString();
}
Just display the results of that method in a text box, and your good to go =D Hope I explained things well enough and good luck!