Check Boxes

 

StreamReader (Reading a File)

StreamReader is a more streamlined file-reading mechanism, but it does not include the safety mechanism found in FileStream (where the try catch mechanism alerts the programmer to possible failures in opening a file). However, there is a three-statement sequence that you can place before the StreamReader or StreamWriter statements that searches for the file that should be read or written to. These five lines serve the same purpose as try catch:

 if(!File.Exists("KTWeeklyNetWorth.dta")   {     MessageBox.Show("Cannot find file 'KTWeeklyNetWorth.dta'.");     return;   } 

Having passed this file exists test, you can continue with the read or write:

 // Begin file opening and reading with 'StreamReader'. char[] charWNWBlock = new char[47]; // Open existing file 'KTWeeklyNetWorth.dta'. StreamReader qq = new StreamReader("KTWeeklyNetWorth.dta", Encoding.ASCII); qq.ReadBlock(charWNWBlock, 0, 47); string strWNWBlock = new string(charWNWBlock); qq.Close(); 

StreamReader has a large number of overloaded constructors. (Pick Index from the Help menu, then type StreamReader in the search box; you will find reams of information on this subject.) The argument Encoding.ASCII is the default in reading, but there are so many read formats now that one must be careful not to make any rash assumptions about how a record will be read. (In the Help index, enter Encoding and you will see that there are a half- dozen encoding formats.)

There are read mechanisms other than ReadBlock, but this is the most common because most files consist of records that are all the same length. ReadBlock places the record that is read into a char buffer (not string). So it is usually appropriate to place the record into a string immediately. In the case shown above, strWNWBlock is a local variable, but in most cases this variable would be declared at the top of the project as global to the form so the results of the read can be used elsewhere:

 public string strWNWBlock; 

Once the record is placed into a string, it can immediately be parsed into its individual string variables using the Substring statement:

 // Read strShortYW, strYW, strTTWorth, strTTCost, and strTTGainLoss. wow.ReadBlock(charWNWBlock, 0, 47); strWNWBlock = new string(charWNWBlock); strShortYW = strWNWBlock.Substring(0, 4); strTTWorth = strWNWBlock.Substring(11, 11);                    etc. 
 


Unlocking Microsoft C# V 2.0 Programming Secrets
Unlocking Microsoft C# V 2.0 Programming Secrets (Wordware Applications Library)
ISBN: 1556220979
EAN: 2147483647
Year: 2005
Pages: 129

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