ToArray() public method

Writes the stream contents to a byte array, regardless of the Position property.
public ToArray ( ) : byte[]
return byte[]
Example #1
0
 /// <summary>
 /// Read stream into byte array. Reads until the end of stream is reached and returns entire stream contents
 /// as a new byte array.
 /// </summary>
 /// <param name="stream">The stream to read data from.</param>
 /// <returns>Returns a new byte array containing the read data.</returns>
 public static byte[] ReadToByteArray(Stream stream)
 {
     using (MemoryBlockStream ms = new MemoryBlockStream())
     {
         stream.CopyTo(ms);
         return(ms.ToArray());
     }
 }
        private void CompareState(MemoryStream ms, MemoryBlockStream ms2)
        {
            // Compare byte content.
            byte[] buff1 = ms.ToArray();
            byte[] buff2 = ms2.ToArray();

            if(!Utils.AreEqual(buff1, buff2)) {
                throw new Exception("State mismatch");
            }

            // Compare read/write position.
            if(ms.Position != ms2.Position) {
                throw new Exception("Position mismatch");
            }
        }
        public void TestWriteZeroBytes()
        {
            byte[] buf = new byte[0];
            MemoryBlockStream ms = new MemoryBlockStream();
            ms.Write(buf, 0, 0);
            Assert.AreEqual(ms.Length, 0);

            XorShiftRandom rng = new XorShiftRandom(1234567);
            byte[] buf2 = new byte[100];
            rng.NextBytes(buf2);
            ms.Write(buf2, 0, buf2.Length);

            if(!Utils.AreEqual(ms.ToArray(), buf2)) Assert.Fail();

            ms.Write(buf, 0, 0);
            Assert.AreEqual(ms.Length, buf2.Length);
        }
Example #4
0
 /// <summary>
 /// Read stream into byte array. Reads until the end of stream is reached and returns entire stream contents
 /// as a new byte array.
 /// </summary>
 /// <param name="stream">The stream to read data from.</param>
 /// <returns>Returns a new byte array containing the read data.</returns>
 public static byte[] ReadToByteArray(Stream stream)
 {
     using(MemoryBlockStream ms = new MemoryBlockStream())
     {
         Copy(stream, ms);
         return ms.ToArray();
     }
 }