12.8 Reading from a File

 <  Day Day Up  >  

You want to read the text from a text-based file, make changes, and write the result back out to the file.


Technique

Section 12.1 used the File.OpenText method to open an existing text file from the local file system. This method returns a StreamReader object that you can use to read text into a string. You can choose to read a single character at a time, a single line at a time, a block of characters , or the entire file at once. To read a single character, use the method Read with no parameters. This method returns an integer value representing the ASCII code of the character, which you can cast to its char equivalent. This method differs with respect to the return value from the other read methods because it returns a “1 if the end of file was reached. The other methods return the integer at the end of a file:

 
 private string OpenText( string file ) {     string result = "";     int curChar = 0;     // open file     StreamReader sr = File.OpenText( file );     // read each character and place in string     while((curChar = sr.Read()) != -1 )         result += (char)curChar;     // close streamreader     sr.Close();     // return result     return result; } 

Instead of reading a file character by character, you can break the reading into blocks by reading a certain number of characters during each read operation. You can use the Read method in this instance as well as the ReadBlock method. Both of these methods use the same number and types of parameters, so either one works the same. To read blocks of character data, create a character array and pass it as the first parameter to the method, followed by the starting index to place the characters at in the array and the number of characters to read. Note that if the number of characters that you request to read is larger than the size of the character array being passed in, an ArgumentException is thrown:

 
 private string OpenText( string file ) {     StreamReader sr = null;     char[] tempBuffer = new char[10];     StringBuilder result = new StringBuilder("");     try     {         sr = File.OpenText( file );         while( sr.Read( tempBuffer, 0, 10 ) != 0 )         {             result.Append(tempBuffer);         }     }     catch( Exception e )     {         MessageBox.Show( e.Message );     }     finally     {         // close streamreader         if( sr != null )             sr.Close();     }     // return result     return result.ToString(); } 

If you want to read the entire file all at once into a string object, call the ReadToEnd method defined in the StreamReader class. It reads the remainder of the file based on the current location of the internal file pointer of the StreamReader class. In other words, if you initially read characters by calling the Read method, calling ReadToEnd would continue where the last Read took place:

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

If you are reading binary files, then use a BinaryReader class to effectively parse the binary data as it comes in. To create a BinaryReader object, pass the FileStream object that was created when the file was opened into the BinaryReader constructor. Several methods within the BinaryReader class read a given .NET data type. For instance, to read an integer, call the ReadInt32 method, and to read a string, call the ReadString method:

 
 private void TestBinaryRead( string file ) {     FileStream fs = null;     BinaryReader br;     int[] intData = new int[5];     string[] strData = new string[5];     try     {         // open the file         fs = File.OpenRead( file );         br = new BinaryReader( fs );         // read 5 integers         for( int i = 0; i < 5; ++i )         {             intData[i] = br.ReadInt32();         }         // read 5 string         for( int i = 0; i < 5; ++i )         {             strData[i] = br.ReadString();         }     }     catch( Exception e )     {         MessageBox.Show( e.Message );     }     finally     {         // close the FileStream         if( fs != null )             fs.Close();     }     // display data     StringBuilder sb = new StringBuilder();     sb.Append( "Int Data: " );     for( int i = 0; i < 5; ++i ) sb.Append( intData[i].ToString() + " " );     sb.Append( "\nString Data: " );     for( int i = 0; i < 5; ++i ) sb.Append( strData[i] + " " );     MessageBox.Show( sb.ToString() );     return; } 

Comments

Reading a file character-by-character has performance issues associated with it for large files. If you don't need character-by-character processing, then the remaining methods are faster. That being said, even if you are doing character-by-character processing, reading larger chunks of data and then parsing the in-memory representation would eliminate any performance issues. In any case, if your application is designed to work with large files, Chapter 22 demonstrates how to use threading to create worker threads while leaving the user -interface thread free to process incoming events.

In the previous section, you saw how to write binary data by utilizing the Write method defined in the BinaryWriter class. When using the BinaryReader and BinaryWriter classes together, you can easily start to formulate custom file formats merely by keeping the reading and writing in synch. For instance, if your application consists of a series of records, each of which contains four integer values followed by two strings and then five bool values, you can easily begin to create your own parser to write that data in the format one record at a time and subsequently read any file using that format with the BinaryReader class.

 <  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