Using IEnumerable to read a file
I'm a very big fan of readable code, that is why I use a lot of foreach statements, and I would like to iterate through all the buffers of a specific file and then do something on them. So why not use the IEnumerable interface for this. The following simple example is just that.
The first thing we need to do is make a method that returns an IEnumerable<byte[]>. This way we can use an foreach statement on the method. Then we need to open our file, very convenient with a using statement so we can be sure that whatever happens the filestream will be closed and we don't hold resources to long.
class Program {
public static IEnumerable<byte[]> GetBuffers(string filename) {
int numBytes = 0;
using (FileStream fs = new FileStream(filename, FileMode.Open)) {
do {
byte[] buffer = new byte[1024 * 8];
numBytes = fs.Read(buffer, 0, 1024 * 8);
if (numBytes > 0) {
yield return buffer;
}
} while (numBytes > 0);
}
}
static void Main(string[] args) {
foreach (byte[] buffer in Program.GetBuffers
(@"testfile.dat")) {
Console.WriteLine(buffer.Length);
}
Console.ReadLine();
}
}
At this moment it is really easy to access the buffers in the stream and take action on the buffers. Off course there should be some exceptionhandling, but that is easy enough.