Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reliable way to convert a file to a byte[]

Tags:

c#

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    fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));     //Close the File Stream    fs.Close();    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?

like image 442
JL. Avatar asked Sep 30 '09 13:09

JL.


People also ask

How do I turn a byte into a file?

Java – How to save byte[] to a filewrite is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths. get("/path/file"); Files. write(path, bytes);

What is byte array format?

A byte is 8 bits (binary data). A byte array is an array of bytes (tautology FTW!). You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.


2 Answers

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.

like image 118
Erik Forbes Avatar answered Sep 21 '22 21:09

Erik Forbes


byte[] bytes = File.ReadAllBytes(filename)  

or ...

var bytes = File.ReadAllBytes(filename)  
like image 36
Brian Rasmussen Avatar answered Sep 23 '22 21:09

Brian Rasmussen