We can read bytes from Filestream with the help of two methods: ReadBytes() and another is Read(). If we use ReadByte() method then eachtime when it is called , it reads a single byte from the file and returns an integer value.it returns -1 when the end of the file is encountered.And we use Read() for reading block of bytes.
[General form of ReadByte()]
Int ReadByte()
[General form of Read()]
Int Read(byte[] buffer,int offset,int bytesLength)
Read() reads up to byteLength into buffer starting at offset.it return the number of bytes successfully read.
Example
In the following example function Getbytes return byte[].
private static byte[] GetBytes(string FilePath) { byte[] fileInbytes; FileStream fileStream = null; try { fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read); } catch (FileNotFoundException ex) { MessageBox.Show("File is not found"); return null; } catch (Exception exc) { MessageBox.Show(exc.Message); return null; } int FileStreamLength = (int)fileStream.Length; // total number of bytes read int numBytesReadPosition = 0; // actual number of bytes read fileInbytes = new byte[FileStreamLength]; while (FileStreamLength > 0) { // Read may return anything from 0 to numBytesToRead. int n = fileStream.Read(fileInbytes, numBytesReadPosition, FileStreamLength); // Break when the end of the file is reached. if (n == 0) break; numBytesReadPosition += n; FileStreamLength -= n; } return fileInbytes; }