RSS

How to safely read file stream using C#

Mon, Jun 30, 2008

Programming, Tutorials

Following example shows how do we safely read the file using FileStream in C#.
By calling FileStream.Read method in a loop we can gurantee whole file is correctly read.

Example showing how can we read file safely using FileStream

i. Create FileStream to open the file for reading.
ii. Call FileStream.Read until all the content from file is read.
ii. Close the file stream.

 public static byte[] ReadingFileSafely(string path)
{
    byte[] myBuffer;
    FileStream myStream = new FileStream(path, FileMode.Open, FileAccess.Read);
    //Start reading file to buffer
    try
    {
        int len = (int)myStream.Length;
        myBuffer = new byte[len];
        int count;
        int total = 0;
        while ((count = myStream.Read(myBuffer, total, len - total)) > 0)
            total += count; 
    }
    finally
    {
        myStream.Close();
    }
    return myBuffer;
}
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

, ,

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.