CHAPTER 16 538 THE SYSTEM.IO NAMESPACE Working (Web design course)

CHAPTER 16 538 THE SYSTEM.IO NAMESPACE Working with BinaryWriters and BinaryReaders The final writer/reader sets you will examine here are BinaryReader and BinaryWriter, both of which derive directly from System.Object. These types allow you to read and write discrete data types to an underlying stream in a compact binary format. The BinaryWriter class defines a highly overloaded Write() method to place a data type in the underlying stream. In addition to Write(), BinaryWriter provides additional members that allow you to get or set the Stream-derived type and offers support for random access to the data (see Table 16-9). Table 16-9. BinaryWriter Core Members Member Meaning in Life BaseStream This read-only property provides access to the underlying stream used with the BinaryWriter object. Close() This method closes the binary stream. Flush() This method flushes the binary stream. Seek() This method sets the position in the current stream. Write() This method writes a value to the current stream. The BinaryReader class complements the functionality offered by BinaryWriter with the members described in Table 16-10. Table 16-10. BinaryReader Core Members Member Meaning in Life BaseStream This read-only property provides access to the underlying stream used with the BinaryReader object. Close() This method closes the binary reader. PeekChar() This method returns the next available character without actually advancing the position in the stream. Read() This method reads a given set of bytes or characters and stores them in the incoming array. ReadXXXX() The BinaryReader class defines numerous ReadXXXX() methods that grab the next type from the stream (ReadBoolean(), ReadByte(), ReadInt32(), and so forth). The following example writes a number of data types to a new *.dat file: static void Main(string[] args) { // Open a binary writer for a file. FileInfo f = new FileInfo(”BinFile.dat”); BinaryWriter bw = new BinaryWriter(f.OpenWrite()); // Print out the type of BaseStream. // (System.IO.FileStream in this case). Console.WriteLine(”Base stream is: {0}”, bw.BaseStream); // Create some data to save in the file double aDouble = 1234.67; int anInt = 34567; char[] aCharArray = { ‘A’, ‘B’, ‘C’ };
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

Leave a Reply