Reading a file in Managed Code [Lakshan Fernando]

Reading a file in Managed Code [Lakshan Fernando]

  • Comments 2

Some of our new users to managed code take a little time to get used to the design pattern in reading a file. I thought I’ll enumerate through the most common patterns for their benefit;

 

Reading from a FileStream: Create a suitable buffer size – the default internal buffer size is 4k for a FileStream – and read until the returned value is 0, which indicates the end of the stream. Remember to work with the returned value size when processing the data. Although our Stream Read implementations generally try hard to return the requested number of bytes, its not guaranteed and the Read contract specifies that you should only work with the returned value.

 

            String fileName =...;

            using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))

            {

                int size = 4096;

                Byte[] bits = new Byte[size];

                int count;

                while ((count = stream.Read(bits, 0, size)) != 0)

                {

                    //bits buffer has valid data from 0 to count-1 that can be processed here

                    ...

                }

            }

 

Reading from a text file: The StreamReader has some convenient methods to read from it, where ReadLine() is the most popular;

 

            String fileName =...

            using (StreamReader reader = new StreamReader(fileName))

            {

                String line;

                while ((line = reader.ReadLine()) != null)

                {

                    //process the line

                }

            }

StreamReader also has a method to read the whole file, ReadToEnd(), but it has some gotchas which the documentation covers well. You can also use Read(Char[], int, int) similar to FileStream.Read method above if you want to work with characters.

 

  • For the lazy users, File.ReadAllBytes and File.ReadAllText static methods read an entire file to a byte[]/string.
Page 1 of 1 (2 items)