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?
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);
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.
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.
byte[] bytes = File.ReadAllBytes(filename)
or ...
var bytes = File.ReadAllBytes(filename)
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