FileStream Read File [C#]
This example shows how to safely read file using FileStream in C#. To be sure the whole file is correctly read, you should call FileStream.Read method in a loop, even if in the most cases the whole file is read in a single call of FileStream.Read method.
Read file using FileStream
First create FileStream to open a file for reading. Then call FileStream.Read in a loop until the whole file is read. Finally close the stream.
[C#]using System.IO; public static byte[] ReadFile(string filePath) { byte[] buffer; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); try { int length = (int)fileStream.Length; // get file length buffer = new byte[length]; // create buffer int count; // actual number of bytes read int sum = 0; // total number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) sum += count; // sum is a buffer offset for next reading } finally { fileStream.Close(); } return buffer; }
Files and Folders Examples
- [C#] FileStream Open File – how to open file using file stream
- [C#] FileStream Read File – how to safely read file stream
- [C#] Read Text File – how to read lines from text file
- [C#] Load Text File to String – how to load text from file to string
- [C#] Get Files from Directory – how to get files from directory
- [C#] Delete All Files – how to delete files from the specified directory
- [C#] Get Application Directory – how to get application or assembly folder
- [C#] File Attributes – how to get or set file attributes
- [C#] Get File Time – how to get last modification time of a file
- [C#] Open File With Associated Application – how to launch the default application
See also
- FileStream – MSDN – class to access file using stream interface
- FileStream.Read – MSDN – file stream read method