Wim De Cleen

Absorbed in software thoughts

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

Events

Belgian Bloggers

Internet Explorer

General.NET

Service-Oriented Architecture (SOA)

Other links

Subscriptions

Post Categories



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.

posted on Sunday, November 12, 2006 7:44 PM by widec





Powered by Dot Net Junkies, by Telligent Systems