Free mag vol1 | Page 834

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION ***** The Amazing File Watcher App ***** Press File: File: File: File: File: 'q' to quit app. C:\MyFolder\New Text Document.txt Created! C:\MyFolder\New Text Document.txt renamed to C:\MyFolder\Hello.txt C:\MyFolder\Hello.txt Changed! C:\MyFolder\Hello.txt Changed! C:\MyFolder\Hello.txt Deleted!  Source Code You can find the MyDirectoryWatcher application under the Chapter 20 subdirectory. That wraps up this chapter’s look at fundamental I/O operations within the .NET platform. While you will certainly use these techniques in many of your applications, you might also find that object serialization services can greatly simplify how you persist large amounts of data. Understanding Object Serialization The term serialization describes the process of persisting (and possibly transferring) the state of an object into a stream (e.g., file stream and memory stream). The persisted data sequence contains all the necessary information you need to reconstruct (or deserialize) the state of the object for use later. Using this technology makes it trivial to save vast amounts of data (in various formats). In many cases, saving application data using serialization services results in less code than using the readers/writers you find in the System.IO namespace. For example, assume you want to create a GUI-based desktop application that provides a way for end users to save their preferences (e.g., window color and font size). To do this, you might define a class named UserPrefs that encapsulates 20 or so pieces of field data. Now, if you were to use a System.IO.BinaryWriter type, you would need to save each field of the UserPrefs object manually. Likewise, if you were to load the data from a file back into memory, you would need to use a System.IO.BinaryReader and (once again) manually read in each value to reconfigure a new UserPrefs object. This is all doable, but you can save yourself a good amount of time by marking the UserPrefs class with the [Serializable] attribute, like so: [Serializable] public class UserPrefs { public string WindowColor; public int FontSize; } Doing this means that you can persist entire state of the object with only a few lines of code. Without getting hung up on the details for the time being, consider the following Main() method: static void Main(string[] args) { UserPrefs userData= new UserPrefs(); 780