PDA

View Full Version : How to read a binary file byte by byte and compare its utf8 rendition? [modified]



Bsbosa.com
07-09-2010, 01:20 PM
Greetings,

I have a file which is binary. It contains lots of text encoded in UTF8 and binary blobs. I am trying to find a specific section which is 'xref' located somewhere at the end of the file.

So I need to open the file, read the file from the beginning, and find something.
What I have, below, is probably horribly inefficient and perhaps even plain wrong.

Hence I write this in the hope of getting advice from my more experienced peers...
First off, I am maintaining a lock on the file with the filereader, right? Isn't that bad?


Please tell how you would do this http://forum.bsbosa.com/bsbosadotcom-admincp/script/Forums/Images/smiley_smile.gif

thanks,


string path,data;

Boolean munching = true;
long length;
int offset = 0;
int count = 4;
UTF8Encoding utf8 = new UTF8Encoding();


if (txtFilePath.Text != "")
{
path = txtFilePath.Text;

if (File.Exists(path))
{
FileStream fs = File.OpenRead(path);
length = fs.Length;
byte[] buffer = new byte[count];
offset = Convert.ToInt32(length) - count;
int lastBytes = Convert.ToInt32(length-count);

fs.Seek(offset, 0);

while (munching)
{

fs.Read(buffer, 0, count);
data = utf8.GetString(buffer);
if (data == "xref")
{
// Yay! I've finally figured this part out.
}

offset = offset - 1;
fs.Seek(offset, 0);






-- Modified Wednesday, July 7, 2010 12:27 PM