Game Development Reference
In-Depth Information
•
an
XMLReader
reads XML things from an underlying stream
•
a
TextReader
reads text things from an underlying something
•
a
StreamReader
reads text things from an underlying stream
•
a
StringReader
reads text things from an underlying string
The confusing thing is that the name of the reader sometimes indicates
what
is being
read, and sometimes
from where
it is reading data.
22.5.5 Stream Reader
The most common way to read a file is by using a
StreamReader
object. This is a
TextReader
using an underlying stream, meaning that if you want to use this kind of
reader, you first need to have a
Stream
. There are many different kinds of streams, but
again the most common one is the
FileStream
.Usingthe
FileStream
in combination
with a
StreamReader
is illustrated by the following lines of code:
FileStream s =
new
FileStream("test.txt", FileMode.Open);
StreamReader r =
new
StreamReader(s);
string
t = r.ReadToEnd();
Because of the highly common combination of the
StreamReader
with the
FileStream
,
the
StreamReader
class has a constructor that takes a file name as parameter and that
creates the
FileStream
object itself. A
FileMode
parameter is no longer necessary in
this case, because we always want to open an existing file when reading. So, what
remains is the following code:
StreamReader r =
new
StreamReader("test.txt");
string
t = r.ReadToEnd();
By the way, there is an even shorter way to read all the text from a file, because
the
File
class has a static method
ReadAllText
that creates the
StreamReader
and calls
ReadToEnd
. This results in the following (single line of) code:
string
t = File.ReadAllText("test.txt");
The libraries available in C# have many of these shortcuts, but sometimes you may
want to do something slightly different from what the shortcut dictates. In that case,
you need to take the long approach and you need to know how everything works
behind the scenes.
22.5.6 Abstract Classes
We mentioned earlier on that
TextReader
is an abstract class. The
Stream
,
Tex t W r i t e r
,
XmlReader
and
XmlWriter
classes are also abstract. This means that it is not allowed to