Php web hosting - CHAPTER 16 THE SYSTEM.IO NAMESPACE 539 //
CHAPTER 16 THE SYSTEM.IO NAMESPACE 539 // Write the data bw.Write(aDouble); bw.Write(anInt); bw.Write(aCharArray); bw.Close(); } Notice how the FileStream object returned from FileInfo.OpenWrite() is passed to the constructor of the BinaryWriter type. Using this technique, it is very simple to layer in a stream before writing out the data. Do understand that the constructor of BinaryWriter takes any Stream-derived type (e.g., FileStream, MemoryStream, or BufferedStream). Thus, if you would rather write binary data to memory, simply supply a valid MemoryStream object. To read the data out of the BinFile.dat file, the BinaryReader type provides a number of options. Here, you will make use of PeekChar() to determine if the stream still has data to provide and, if so, use ReadByte() to obtain the value. Note that you are formatting the bytes in hexadecimal and inserting seven spaces between each: static void Main(string[] args) { // Open a binary writer for a file. FileInfo f = new FileInfo(”BinFile.dat”); … // Read the data as raw bytes BinaryReader br = new BinaryReader(f.OpenRead()); int temp = 0; while (br.PeekChar() != -1) { Console.Write(”{0,7:x} “, br.ReadByte()); if (++temp == 4) { // Write a new line every 4 bytes Console.WriteLine(); temp = 0; } } Console.WriteLine(); } The output of this program appears in Figure 16-9. Figure 16-9. Reading bytes from a binary file
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.