CHAPTER 16 532 THE SYSTEM.IO (Web hosting billing) NAMESPACE Table
CHAPTER 16 532 THE SYSTEM.IO NAMESPACE Table 16-6. Abstract StreamMembers Members Meaning in Life CanRead Determine whether the current stream supports reading, seeking, and/or CanSeek writing. CanWrite Close() Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Flush() Updates the underlying data source or repository with the current state of the buffer and then clears the buffer. If a stream does not implement a buffer, this method does nothing. Length Returns the length of the stream, in bytes. Position Determines the position in the current stream. Read() Read a sequence of bytes (or a single byte) from the current stream and advance ReadByte() the current position in the stream by the number of bytes read. Seek() Sets the position in the current stream. SetLength() Sets the length of the current stream. Write() Write a sequence of bytes (or a single byte) to the current stream and advance WriteByte() the current position in this stream by the number of bytes written. Working with FileStreams The FileStream class provides an implementation for the abstract Stream members in a manner appropriate for file-based streaming. It is a fairly primitive stream; it can read or write only a single byte or an array of bytes. In reality, you will not often need to directly interact with the members of the FileStream type. Rather, you will most likely make use of various stream wrappers, which make it easier to work with textual data or .NET types. Nevertheless, for illustrative purposes, let s experiment with the synchronous read/write capabilities of the FileStream type. Assume you have a new console application named FileStreamApp. Your goal is to write a simple text message to a new file named myMessage.dat. However, given that FileStream can operate only on raw bytes, you will be required to encode the System.String type into a corresponding byte array. Luckily, the System.Text namespace defines a type named Encoding, which provides members that encode and decode strings to (or from) an array of bytes (check out the .NET Framework 2.0 SDK documentation for full details of the Encoding type). Once encoded, the byte array is persisted to file using the FileStream.Write() method. To read the bytes back into memory, you must reset the internal position of the stream (via the Position property) and call the ReadByte() method. Finally, you display the raw byte array and the decoded string to the console. Here is the complete Main() method: // Don’t forget to ‘use’ System.Text. static void Main(string[] args) { Console.WriteLine(”***** Fun with FileStreams *****n”); // Obtain a FileStream object. FileStream fStream = File.Open(@”C:myMessage.dat”, FileMode.Create);
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.