Working with Files: Take Two

While the use of StreamReader and StreamWriter is great to deal with text files, they fall short in providing byte-level access to a file. Other methods on the File class used to open or create files expose FileStream objects, which allow for richer manipulation of the data contained in a file. For example:

using (FileStream fs = File.OpenRead(@"c:\windows\system32\notepad.exe")){    var m = (char)fs.ReadByte();    var z = (char)fs.ReadByte();    Console.WriteLine("{0}{1}", m, z);}

This trivial example shows how to obtain a FileStream object that can read from the specified file. It uses the ReadByte method two times to read the first 2 bytes of an executable file, which are always MZ, ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.