29

I would like to know how to convert a stream to a byte.

I find this code, but in my case it does not work:

var memoryStream = new MemoryStream();
paramFile.CopyTo(memoryStream);
byte[] myBynary = memoryStream.ToArray();
myBinary = memoryStream.ToArray();

But in my case, in the line paramFile.CopyTo(memoryStream) it happens nothing, no exception, the application still works, but the code not continue with the next line.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193

2 Answers2

45

If you are reading a file just use the File.ReadAllBytes Method:

byte[] myBinary = File.ReadAllBytes(@"C:\MyDir\MyFile.bin");

Also, there is no need to CopyTo a MemoryStream just to get a byte array as long as your sourceStream supports the Length property:

byte[] myBinary = new byte[paramFile.Length];
paramFile.Read(myBinary, 0, (int)paramFile.Length);
JamieSee
  • 12,696
  • 2
  • 31
  • 47
  • 1
    really I have a stream, no the file. Although the original data is a file, but I send the file into the stream in the WCF. So I need to convert the stream to a byte[]. But this way not works, because the length property is a long, and the read method use an int. – Álvaro García Jun 29 '12 at 18:07
  • 1
    As long as you don't exceed 2147483647 (int.MaxValue) bytes this works fine. Otherwise you have to assemble the array with a counter. – JamieSee Jun 29 '12 at 18:32
43

This is an extension method i wrote for the Stream class

 public static class StreamExtensions
    {
        public static byte[] ToByteArray(this Stream stream)
        {
            stream.Position = 0;
            byte[] buffer = new byte[stream.Length];
            for (int totalBytesCopied = 0; totalBytesCopied < stream.Length; )
                totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);
            return buffer;
        }
    }
Athens Holloway
  • 2,183
  • 3
  • 17
  • 26
  • Athens, I don't suppose you have an extra FromByteArray method laying around? :-) I'm using your method, I just need to be able to convert it back now. – Jason Hartley Jul 23 '13 at 16:00
  • 1
    This may help. http://stackoverflow.com/questions/4736155/how-do-i-convert-byte-to-stream-in-c – Athens Holloway Jul 25 '13 at 19:52