Free mag vol1 | Page 824

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION 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. However, you will not often need to interact directly with the members of the FileStream type. Instead, you will probably use various stream wrappers, which make it easier to work with textual data or .NET types. Nevertheless, you will find it helpful to experiment with the synchronous read/write capabilities of the FileStream type. Assume you have a new Console Application named FileStreamApp (and verify that System.IO and System.Text are imported into your initial C# code file). 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. Fortunately, the System.Text namespace defines a type named Encoding that provides members that encode and decode strings to (or from) an array of bytes (check out the .NET Framework 4.5 SDK documentation for more details about the Encoding type). Once encoded, the byte array is persisted to file with the FileStream.Write() method. To read the bytes back into memory, you must reset the internal position of the stream (using 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 import the System.Text and System.IO namespaces. static void Main(string[] args) { Console.WriteLine("***** Fun with FileStreams *****\n"); // Obtain a FileStream object. using(FileStream fStream = File.Open(@"C:\myMessage.dat", FileMode.Create)) { // Encode a string as an array of bytes. string msg = "Hello!"; byte[] msgAsByteArray = Encoding.Default.GetBytes(msg); // Write byte[] to file. fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length); // Reset internal position of stream. fStream.Position = 0; // Read the types from file and display to console. Console.Write("Your message as an array of bytes: "); byte[] bytesFromFile = new byte[msgAsByteArray.Length]; for (int i = 0; i < msgAsByteArray.Length; i++) { bytesFromFile[i] = (byte)fStream.ReadByte(); Console.Write(bytesFromFile[i]); } // Display decoded messages. Console.Write("\nDecoded Message: "); Console.WriteLine(Encoding.Default.GetString(bytesFromFile)); 770