The Stream Classes


C# defines both byte and character stream classes. However, the character stream classes are really just wrappers that convert an underlying byte stream into a character stream, handling any conversion automatically. Thus, the character streams, while logically separate, are built upon byte streams.

All stream classes are defined within the System.IO namespace. To use these classes, you will usually include the following statement near the top of your program:

 using System.IO; 

The reason that you don’t have to specify System.IO for console input and output is that the Console class is defined in the System namespace.

The Stream Class

At the core of C#’s streams is System.IO.Stream. Stream represents a byte stream and is a base class for all other stream classes. It is also abstract, which means that you cannot instantiate a Stream object. Stream defines a set of standard stream operations. Table 14-1 shows several commonly used methods defined by Stream.

Table 14-1: Some of the Methods Defi ned by Stream

Method

Description

void Close( )

Closes the stream.

void Flush( )

Writes the contents of the stream to the physical device.

int ReadByte( )

Returns an integer representation of the next available byte of input. Returns 1 when the end of the fi le is encountered.

int Read(byte[ ] buf, int offset, int numBytes)

Attempts to read up to numBytes bytes into buf starting at buf[offset], returning the number of bytes successfully read.

long Seek(long offset, SeekOrigin origin)

Sets the current position in the stream to the specifi ed offset from the specifi ed origin.

void WriteByte(byte b)

Writes a single byte to an output stream.

void Write(byte[ ] buf, int offset, int numBytes)

Writes a subrange of numBytes bytes from the array buf, beginning at buf[offset].

In general, if an I/O error occurs, the methods shown in Table 14-1 will throw an IOException. If an invalid operation is attempted, such as attempting to write to a stream that is read-only, a NotSupportedException is thrown.

Notice that Stream defines methods that read and write data. However, not all streams will support both of these operations, because it is possible to open read-only or write-only streams. Also, not all streams will support position requests via Seek( ). To determine the capabilities of a stream, you will use one or more of Stream’s properties. They are shown in Table 14-2.

Table 14-2: The Properties Defi ned by Stream

Method

Description

bool CanRead

This property is true if the stream can be read. This property is read-only.

bool CanSeek

This property is true if the stream supports position requests. This property is read-only.

bool CanTimeout

This property is true if the stream can time out. This property is read-only. (Added by .NET Framework 2.0.)

bool CanWrite

This property is true if the stream can be written. This property is read-only.

long Length

This property contains the length of the stream. This property is read-only.

long Position

This property represents the current position of the stream. This property is read/write.

int ReadTimeout

This property represents the length of time before a time-out will occur for read operations. This property is read/write. (Added by .NET Framework 2.0.)

int WriteTimeout

This property represents the length of time before a timeout will occur for write operations. This property is read/write. (Added by .NET Framework 2.0.)

The Byte Stream Classes

From Stream are derived the six concrete byte stream classes shown here:

Stream Class

Description

BufferedStream

Wraps a byte stream and adds buffering. Buffering provides a performance enhancement in many cases.

Compression.DeflateStream

Wraps a byte stream and provides for compression/decompression of data. (Added by .NET Framework 2.0.)

Compression.GZipStream

Wraps a byte stream and provides for compression/decompression of data. It uses the GZIP format. (Added by .NET Framework 2.0.)

FileStream

A byte stream designed for file I/O.

MemoryStream

A byte stream that uses memory for storage.

UnmanagedMemoryStream

A byte stream that uses memory for storage, but is not suitable for mixed-language programming. (Added by .NET Framework 2.0.)

It is also possible for you to derive your own stream classes. However, for the vast majority of applications, the built-in streams will be sufficient.

The Character Stream Wrapper Classes

To create a character stream, wrap a byte stream inside one of C#’s character stream wrappers. At the top of the character stream hierarchy are the abstract classes TextReader and TextWriter. TextReader handles input and TextWriter handles output. The methods defined by these two abstract classes are available to all of their subclasses. Thus, they form a minimal set of I/O functions that all character streams will have.

Table 14-3 shows the input methods in TextReader. In general, these methods can throw an IOException on error. (Some can throw other types of exceptions, too.) Of particular interest is the ReadLine( ) method, which reads an entire line of text, returning it as a string. This method is useful when reading input that contains embedded spaces.

Table 14-3: The Input Methods Defi ned by TextReader

Method

Description

void Close( )

Closes the stream.

int Peek( )

Obtains the next character from the input stream, but does not remove that character. Returns –1 if no character is available.

int Read( )

Returns an integer representation of the next available character from the invoking input stream. Returns –1 when the end of the stream is encountered.

int Read(char[ ] buf, int offset, int numChars)

Attempts to read up to numChars characters into buf starting at buf[offset], returning the number of characters successfully read.

int ReadBlock(char[ ] buf, int offset, int numChars)

Attempts to read up to numChars characters into buf starting at buf[offset], returning the number of characters successfully read.

string ReadLine( )

Reads the next line of text and returns it as a string. Null is returned if an attempt is made to read at end-of-file.

string ReadToEnd( )

Reads all of the remaining characters in a stream and returns them as a string.

TextWriter defines versions of Write( ) and WriteLine( ) that output all of the built-in types. For example, here are just a few of their overloaded versions:

Method

Description

void Write(int val)

Write an int.

void Write(double val)

Write a double.

void Write(bool val)

Write a bool.

void WriteLine(string val)

Write a string followed by a newline.

void WriteLine(uint val)

Write a uint followed by a newline.

void WriteLine(char val)

Write a character followed by a newline.

TextWriter also defines the Close( ) and Flush( ) methods shown here:

 virtual void Close( ) virtual void Flush( )

Flush( ) causes any data remaining in the output buffer to be written to the physical medium. Close( ) closes the stream.

The TextReader and TextWriter classes are implemented by several character-based stream classes, including those shown here. Thus, these streams provide the methods and properties specified by TextReader and TextWriter.

Stream Class

Description

StreamReader

Read characters from a byte stream. This class wraps a byte input stream.

StreamWriter

Write characters to a byte stream. This class wraps a byte output stream.

StringReader

Read characters from a string.

StringWriter

Write characters to a string.

Binary Streams

In addition to the byte and character streams, C# defines two binary stream classes that can be used to read and write binary data directly. These streams are called BinaryReader and BinaryWriter. We will look closely at these later in this chapter when binary file I/O is discussed.

Now that you understand the general layout of the C# I/O system, the rest of this chapter will examine its various pieces in detail, beginning with console I/O.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net