Wednesday 14 November 2012

CSharp: Read bytes from File

Question:
How to read bytes from a file?
How to read a file as a byte array?


Answer:


There is a simple method for it

byte[] bytes = File.ReadAllBytes("c:\folder\file.ext");

There is a way less memory intensive

Stream myDestinationStream = ...; using(Stream mySource = File.OpenRead(myFilePath)) { byte[] myBuffer = new byte[2048]; int myBytesRead; while((myBytesRead= mySource.Read(myBuffer , 0, myBuffer .Length)) > 0) { myDestinationStream.Write(myBuffer , 0, myBytesRead); } }

1 comment:

Anonymous said...

Since version 4 of the .Net Framework, there's a method called "CopyTo" in the Stream class that does exactly that.
http://msdn.microsoft.com/en-us/library/dd782932(v=vs.100).aspx
It's also available in Silverlight.