Tuesday, November 1, 2011

Read Stream from a file in chuncks

Problem
I had a programming requirement where I need to read from a file but only 32kb could be transferred at a time. So how do we do that.

Solution
Solution to that problem is that we use binary reader to read only the chunk of data from the file then we use filewriter to write the file.


int chunkSize = 1024;
byte[] chunk = new byte[chunkSize];
         
string destinationPath = @"C:\Users\faraz\MyFileDestination\"+_filename;
string filepath = @"C:\Users\"+targetFile;
using (FileStream fileReader = new FileStream(filepath, FileMode.Open, FileAccess.Read) )
{
      FileStream filewriter = new FileStream(destinationPath, FileMode.Create, FileAccess.ReadWrite);
      BinaryReader binaryReader = new BinaryReader(fileRead);

      int bytesToRead = (int)fileReader.Length;

      do
      {
              chunk = binaryReader.ReadBytes(chunkSize);
              filewriter.Write(chunk, 0, chunk.Length);
              bytesToRead -= chunkSize;
      } while (bytesToRead > 0);

      filewriter.Close();
      binaryReader.Close();    
}
            
            ResultLlabel.Text = @"File Was written successfully.";