0
private bool ReadMagic(BinaryReader reader) 
{ 
     try 
     { 
          ini: 

          byte b0 = reader.ReadByte(); 
          if (b0 != 0xF9) goto ini; 

          b0 = reader.ReadByte(); 
          if (b0 != 0xbe) goto ini; 

          b0 = reader.ReadByte(); 
          if (b0 != 0xb4) goto ini; 

          b0 = reader.ReadByte(); 
          if (b0 != 0xd9) goto ini; 

          return true; 
     } 
     catch (EndOfStreamException) 
     { 
          return false; 
     } 
}

I found this piece of code on github and was wondering why someone would use the ReadMagic function instead of the usual reader.Read() function? Also could someone explain how the ReadMagic function works?

using(var reader = command.ExecuteReader())
{
     while(ReadMagic(reader));
}
2
  • 1
    goto? Amazing... Commented Jul 1, 2016 at 16:33
  • var seq = new byte[] {0xF9, 0xbe, 0xb4, 0xd9}; int currentIndex = 0; while(!reader.EndOfStream) { if(reader.ReadByte() == seq[currentIndex]) currentIndex++; else currentIndex = 0; if(currentIndex == seq.Length) return true;} return false; Commented Jul 1, 2016 at 16:52

1 Answer 1

4

A SqlDataReader is very much not the same thing as a BinaryReader, and you wouldn't use it as such. The BinaryReader is for reading streams (eg reading from a file). It has methods such as ReadByte, used here, for reading actual bytes from the stream, whereas SqlDataReader uses Read to advance to the next returned row, if there is one.

It looks like the ReadMagic function is consuming bytes from the stream until it gets a series of 0xF9, 0xBE, 0xB4, 0xD9 - presumably some sort of marker in whatever stream it happens to be reading, then returning true upon finding it.

Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense. Thanks for the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.