-2

I want to make a program which allows users to search for a specific hex code within a file and the output would be the offset or not found . The code that i have so far is :

 namespace search
 {
class Program
{
    static void Main(string[] args)
    {
        System.IO.BinaryWriter bw = new BinaryWriter(File.OpenWrite("C:\\1.txt"));
        bw.BaseStream.Position = 3;
        bw.Write((byte)0x01);
        bw.Close();
        Console.WriteLine("Wrote the byte 01 at offset 3!");
    }
}

}

I have looked everywhere on the web and did not found anything usefull , is it possible to search for hex code and have an output with the offset ?

EDIT1:

Lets say we have this file 1.txt and at this offset 0x1300 we have this hex code 0120 / 0x01 0x20 / "0120" ( i dont know how to write it ) . After opening the program it will ask you with a console.readline what hex code to search for and the output will be 0x1300

EDIT2: my question is similar to this one VB.Net Get Offset Address and it have a solution but in vb.net

Community
  • 1
  • 1
  • 1
    Did you look at the `BinaryReader` class as well? – Rowland Shaw Oct 26 '13 at 17:49
  • By hex code, do you mean byte? – Tim S. Oct 26 '13 at 17:51
  • @TimS. I am not really sure , after all the searching i did I am confused . Lets say i have a file called 1.txt , it has at the offset 0x1300 this hex code 0120 , and i want to find it with this program . – user2694190 Oct 26 '13 at 17:52
  • @RowlandShaw yes i did , http://msdn.microsoft.com/de-de/library/system.io.binaryreader.aspx looked at this papers but it only converts the hex code into any value but i need the offset . – user2694190 Oct 26 '13 at 17:56
  • 1
    So try reading your file, byte at a time until (counting as you go) until you find the right byte? – Rowland Shaw Oct 26 '13 at 17:57
  • @RowlandShaw yes thats right and give the user the offset :) – user2694190 Oct 26 '13 at 18:00
  • Sounds just like http://stackoverflow.com/questions/3561776/find-sequence-in-ienumerablet-using-linq except that the source sequence is a file stream. – Tim S. Oct 26 '13 at 18:13
  • possible duplicate of [Find an array (byte\[\]) inside another array?](http://stackoverflow.com/questions/4859023/find-an-array-byte-inside-another-array) – Scott Chamberlain Oct 26 '13 at 18:39

1 Answers1

0

This uses BinaryReader to find the byte you wrote to the file.

//Write the byte
BinaryWriter bw = new BinaryWriter(File.OpenWrite("1.txt"));
bw.BaseStream.Position = 3;
bw.Write((byte)0x01);
bw.Close();
Console.WriteLine("Wrote the byte 01 at offset 3!");

//Find the byte
BinaryReader br = new BinaryReader(File.OpenRead("1.txt"));
for (int i = 0; i <= br.BaseStream.Length; i++)
{
     if (br.BaseStream.ReadByte() == (byte)0x01)
     {
          Console.WriteLine("Found the byte 01 at offset " + i);
          break;
     }
}
br.Close();
Zatronium
  • 85
  • 6