Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy one Stream to a byte array with the smallest C# code?

Tags:

c#

.net

stream

Until now I am counting 12 LoCs. Could you make it smaller?

using (Stream fileStream = File.OpenRead(fileName))
{
    using (BinaryReader binaryReader = new BinaryReader(fileStream))
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            byte[] buffer = new byte[256];
            int count;
            int totalBytes = 0;
            while ((count = binaryReader.Read(buffer, 0, 256)) > 0)
            {
                memoryStream.Write(buffer, 0, count);
                totalBytes += count;
            }
            memoryStream.Position = 0;
            byte[] transparentPng = new byte[totalBytes];
            memoryStream.Read(transparentPng, 0, totalBytes);
        }
    }
}
like image 722
Jader Dias Avatar asked Jun 04 '09 13:06

Jader Dias


People also ask

How do you copy a byte array?

copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

Is a byte array a stream?

Streams are commonly written to byte arrays. The byte array is the preferred way to reference binary data in . NET. It can be used to data like the contents of a file or the pixels that make up the bitmap for an image.

How do I get bytes from MemoryStream?

To get the entire buffer, use the GetBuffer method. This method returns a copy of the contents of the MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which this instance has access is returned.

What is byte stream in C#?

Byte streams comprise classes that treat data in the stream as bytes. These streams are most useful when you work with data that is not in a format readable by humans. Stream Class. In the CLR, the Stream class provides the base for other byte stream classes.


1 Answers

There's a static method that can do this for you in one call.

var data = File.ReadAllBytes(fileName);

Alternatively, a method that works for any Stream (that returns its length) would be:

byte[] data;
using (var br = new BinaryReader(stream))
    data = br.ReadBytes((int)stream.Length);

For streams that don't have a well-defined length (e.g. NetworkStream), and thus raise an exception on calling stream.Length, this of course does not work. The slightly more complicated solution presented in Jon Skeet's answer is then what you probably want.

like image 74
Noldorin Avatar answered Oct 26 '22 23:10

Noldorin