Search code examples
c#binaryreaderbinary-serialization

BinaryReader and while statement operators


This is not my code. I am supposed to figure out what is going on. The line of the while statement is where I am confused. Is all its trying to say is read until end of file. I don't understand how it would evaluate to some integer for comparison.

        using (FileStream fs = File.Open(pathToPK, FileMode.Open))
        {
            BinaryReader br = new BinaryReader(fs);

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] buffer = new byte[1024];

                int read = 0;

                while ((read = br.Read(buffer, 0, 1024)) > 0) //don't understand this line
                {
                    ms.Write(buffer, 0, read);
                }

                sk = new byte[ms.ToArray().Length]; //sk is a byte[]

                ms.ToArray().CopyTo(sk, 0);
            }
        }

Solution

  • Basically its opening a filestream in FileMode.Open to a specified file (pathToPK). With said fileStream it then opens a binary reader to read the raw bytes and creates a new MemoryStream to copy the binaryContent.

    Then, it proceeds to read the whole file by chunks of 1024 bytes. Read method of the BinaryReader returns the number of bytes read, so you can read the condition as "while the reader read at least 1 byte (and tried to read as much as 1024)".

    In the end it will create a new byte[] to the length of the whole file, based on the memory stream into which it was copied and actually copy the whole content into sk