0

what I wanted to make is a if statement which checks if the variable which has a offset in it is equal to the base stream length and if it is, it will break.

here is what I have:

//open.FileName is Test.txt which doesn't have the number 123 (aka "7B")
        user_input = "123";
        BinaryReader br = new BinaryReader(File.OpenRead(open.FileName));
        for (int i = 0; i <= br.BaseStream.Length; i++)
        {
            if (i == br.BaseStream.Length) //for some reason this doesn't work. why?
            {
                br.Close();
                operation_Info.Text = operation_Fail;
                break;
            }
            br.BaseStream.Position = i;
            string Locate = br.ReadInt32().ToString();
            if (Locate == user_input)
            {
                br.Close();
                operation_Info.Text = operation_Success;
                break;
            }
         }

For some reason it ignores the if and tries to check for 123 again but gives the error System.IO.EndOfStreamException: 'Unable to read beyond the end of the stream.' sins its already at the end of the file. why doesnt the if work?

Gecko45444
  • 73
  • 1
  • 1
  • 6

2 Answers2

1

Change your 'if' statement to:

if (i == br.BaseStream.Length - 3)

The reason it is failing is because you attempt to read 4 bytes with the ReadInt32() method when you are less than 4 bytes from the end of the stream.

Maximum Cookie
  • 407
  • 3
  • 6
0

Your if statement is unnecessary. You should just change your loop variable so that it only goes to br.BaseStream.Length - 3 instead.

Also, if your text file has the actual string "123" then using ReadInt32 will not work like you think it will. The string "123" is represented by the bytes 0x31 0x32 0x33. Depending on what character appears before it or after it will affect the value that ReadInt32 returns.

For example, if the string has a space before it, then the bytes will be 0x20313233 and the value returned by ReadInt32 will be 858927392 and if there is a space after the 123, the bytes will be 0x31323320 and the returned value will be 540226097.

If you're searching for the numeric value of 123, then the bytes will be 0x7B000000 in the file. The BinaryReader will read them using Big Endian order (assuming Windows).

You should research Big Endian, Little Endian, and how strings and numbers are represented in binary in a file.

Chris Dunaway
  • 10,974
  • 4
  • 36
  • 48