Multiple choice technology programming languages

You need to write a code segment that transfers the first 80 bytes from a stream variable named stream1 into a new byte array named byteArray. You also need to ensure that the code segment assigns the number of bytes that are transferred to an integer variable named bytesTransferred. Which code segment should you use?

  1. for (int i = 0; i < 80; i++) { stream1.WriteByte(byteArray[i]); bytesTransferred = i; if (!stream1.CanWrite) { break; }}

  2. bytesTransferred = stream1.Read(byteArray, 0, 80);

  3. while (bytesTransferred < 80) { stream1.Seek(1, SeekOrigin.Current); byteArray[bytesTransferred++] = Convert.ToByte(stream1.ReadByte());}

  4. stream1.Write(byteArray, 0, 80);bytesTransferred = byteArray.Length;

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The Stream.Read(byte[], offset, count) method reads bytes from the stream into the array and returns the number of bytes actually read. Option B correctly uses this pattern. Option D writes TO the stream instead of reading from it. Options A and C use inefficient manual byte-by-byte loops.

AI explanation

Stream.Read(buffer, offset, count) reads up to count bytes into buffer starting at offset, and returns the actual number of bytes read — exactly matching the requirement to transfer 80 bytes into byteArray and capture the count in bytesTransferred. The other options either write instead of read, or manually loop with ReadByte/Seek in ways that don't correctly track a single bulk read of 80 bytes.