Options:
data.Seek
as suggested by ken2kUse the somewhat simpler Position
property:
data.Position = 0;
Use the ToArray
call in MemoryStream
to make your life simpler to start with:
byte[] buf = data.ToArray();
The third option would be my preferred approach.
Note that you should have a using
statement to close the file stream automatically (and optionally for the MemoryStream
), and I'd add a using directive for System.IO
to make your code cleaner:
byte[] buf;
using (MemoryStream data = new MemoryStream())
{
using (Stream file = TestStream())
{
file.CopyTo(data);
buf = data.ToArray();
}
}
// Use buf
You might also want to create an extension method on Stream
to do this for you in one place, e.g.
public static byte[] CopyToArray(this Stream input)
{
using (MemoryStream memoryStream = new MemoryStream())
{
input.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
Note that this doesn't close the input stream.