Free mag vol1 | Page 818

CHAPTER 20  FILE I/O AND OBJECT SERIALIZATION The FileInfo.Open() Method You can use the FileInfo.Open() method to open existing files, as well as to create new files with far more precision than you can with FileInfo.Create(). This works because Open() typically takes several parameters to qualify exactly how to iterate the file you want to manipulate. Once the call to Open() completes, you are returned a FileStream object. Consider the following logic: static void Main(string[] args) { // Make a new file via FileInfo.Open(). FileInfo f2 = new FileInfo(@"C:\Test2.dat"); using(FileStream fs2 = f2.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { // Use the FileStream object... } } This version of the overloaded Open() method requires three parameters. The first parameter of the Open() method specifies the general flavor of the I/O request (e.g., make a new file, open an existing file, and append to a file), which you specify using the FileMode enumeration (see Table 20-5 for details), like so: public enum FileMode { CreateNew, Create, Open, OpenOrCreate, Truncate, Append } Table 20-5. Members of the FileMode Enumeration 764 Member Meaning in Life CreateNew Informs the OS to make a new file. If it already exists, an IOException is thrown. Create Informs the OS to make a new file. If it already exists, it will be overwritten. Open Opens an existing file. If the file does not exist, a FileNotFoundException is thrown. OpenOrCreate Opens the file if it exists; otherwise, a new file is created. Truncate Opens an existing file and truncates the file to 0 bytes in size. Append Opens a file, moves to the end of the file, and begins write operations (you can only use this flag with a write-only stream). If the file does not exist, a new file is created.