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);
}
}
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With