12.3 Opening a File for Reading Using the File Class

 <  Day Day Up  >  

You want to open a file for reading either text or binary data.


The technique for opening a file is similar to the techniques in Section 12.1, "Creating a New File." However, instead of two methods based on either text or binary formats, opening a file actually has three. The comments section explains why a third method exists.

To open a file for text-based reading, call the OpenText method defined in the File class. Like all methods in the File class, it is static, so you don't need a File object instance. OpenText returns a StreamReader object used to eventually read the textual data from the file:

 private string OpenText( string file ) {     StreamReader sr = null;     try     {         // open the file         sr = File.OpenText( file );     }     catch( Exception e )     {         MessageBox.Show( e.Message );     }     finally     {         // close the StreamReader         if( sr != null )             sr.Close();     }     // placeholder     return ""; } 

To open a file so that its individual byte data can be read, call the OpenRead method. This method returns a FileStream object, which you recall is the same object type used when creating a new binary file:

 private byte[] OpenBinary( string file ) {     FileStream fs = null;     try     {         // open the file         fs = File.OpenRead( file );     }     catch( Exception e )     {         MessageBox.Show( e.Message );     }     finally     {         // close the FileStream         if( fs != null )             fs.Close();     }     // placeholder     return null; } 


Opening a file using the File class is quite similar to the methods for creating a new file. Each method, regardless of the eventual data format, takes a single string parameter denoting the location of the file that you want to work with. A third open method takes additional parameters.

The Open method is a method that combines the ability to open an existing file and create a new file if so desired. In other words, you can use this method in place of any of the methods discussed so far (including the Exists method from Section 12.2, "Verifying the Existence of a File"). Depending on the level of control that you want, there are four overloaded versions of this method with each version allowing more control. The first parameter for these methods is a string representing the filename. If that is the only parameter to the method, then it is equivalent to calling the OpenRead method. The second parameter is a value from the FileMode enumerated data type. This value allows you to control how the file should be accessed in a variety of circumstances. If you specify FileMode.Append , the file is opened and its file pointer set to the end of the file so that any subsequent read or write method calls begin at the end of the file. Of course, calling a read operation at the end of the file results in an exception being thrown. If a file is not found, then a new one is created.

FileMode.Create creates a new file. If the file exists, it is overwritten. FileMode.CreateNew is similar to the previous value, but if the value already exists, an exception is thrown. You can therefore use this value to check for the existence of a file, but rather than take a performance hit to handle the exception, you are better off simply calling the Exists method. You use FileMode.Truncate when a file already exists and you want its contents to be overwritten. If you just want to create a file and have it work regardless of whether the file exists, use the FileMode.Create value.

FileMode.Open and FileMode.OpenOrCreate are similar to the create values just mentioned. The Open value throws an exception if the file does not exist, whereas the OpenOrCreate value does not.

The third optional parameter to the Open method is a flag telling the method what you plan to do with the file. The value is from the FileAccess enumerated data type and can be set to read the file, write to the file, or do both operations. This setting corresponds to the values Read , Write , and ReadWrite , respectively.

Finally, the last parameter is a value used to specify the level of file access for any external threads that want to use the file. You can allow threads to access for reading, writing, doing a combination of the two, or doing nothing at all. If you have the file open for reading, for instance, you want to use FileShare.Read or FileShare.None to prevent external threads from writing to the file as you're trying to read. Very rarely will you want to set the parameter to FileShare.Write . Doing so entails proper synchronization code to ensure data integrity.

 <  Day Day Up  >  

Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net