JL. JL. - 14 days ago 5x
C# Question

Reliable way to convert a file to a byte[]

I found the following code on the web:

private byte [] StreamFile(string filename)
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);

// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];

//Read block of bytes from stream into the byte array

//Close the File Stream
return ImageData; //return the byte data

Is it reliable enough to use to convert a file to byte[] in c#, or is there a better way to do this?

byte[] bytes = System.IO.File.ReadAllBytes(filename);

That should do the trick. ReadAllBytes opens the file, reads its contents into a new byte array, then closes it. Here's the MSDN page for that method.