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

Leave a Reply
You must be logged in to post a comment.