Reading Data

Before you learn about reading XML, you must learn how to read a file. In this section, I’ll cover basic filesystem and network input in .NET. If you’re already familiar with basic I/O types and methods in .NET, feel free to skip to the next section.

I/O classes in .NET are located in the System.IO namespace. The basic object used for reading and writing data, regardless of the source, is the Stream object. Stream is an abstract base class, which represents a sequence of bytes; the Stream has a Read( ) method to read the bytes from the Stream, a Write( ) method to write bytes to the Stream, and a Seek( ) method to set the current location within the Stream. Not all instances or subclasses of Stream support all these operations; for example, you cannot write to a FileStream representing a read-only file, and you cannot Seek( ) to a position in a NetworkStream. The properties CanRead, CanWrite, and CanSeek can be interrogated to determine whether the respective operations are supported by the instance of Stream you’re dealing with.

Table 2-1 shows the Stream type’s subclasses and the methods each type supports.

Table 2-1. Stream subclasses and their supported members

Type

Length

Position

Flush( )

Read( )

Seek( )

Write( )

System.IO.BufferedStream

Yes

Yes

Yes

Yes

Yes

Yes

System.IO.FileStream

Yes

Yes

Yes

Yes

Yes

Yes

System.IO.IsolatedStorage.IsolatedStorageFileStream

Yes

Yes

Yes

Yes

Yes

Yes

System.IO.MemoryStream

Yes ...

Get .NET & XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.