Wednesday, October 15, 2014

Read file using FileStream - Reference - http://www.csharp-examples.net/filestream-read-file/

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;
}

No comments: