Wednesday, August 19, 2009

C#: Read a file into a byte array

public byte[] readByteArrayFromFile(string fileName){
byte[] buff = null;
try{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(fileName).Length;
buff = br.ReadBytes((int)numBytes);
}
catch (Exception ex) {Console.WriteLine(ex.Message); }
return buff;
}

Another option:
byte[] rawData = File.ReadAllBytes("filename");

(This method sacrifices the ability to have more explicit control on the file like FileAccess.Read etc.)

Source: http://kseesharp.blogspot.com/2007/12/read-file-into-byte-array.html

No comments:

Post a Comment