30

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.

1
  • Ah, sorry, param file is the parameter that I receive in the method, is a SystemIO.Stream. Commented Jun 29, 2012 at 17:37

2 Answers 2

44

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
As long as you don't exceed 2147483647 (int.MaxValue) bytes this works fine. Otherwise you have to assemble the array with a counter.
44

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;
        }
    }

2 Comments

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.