03.01.2015 Views

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

Complete set: Intro to C - Bill Buchanan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.9 StreamReader<br />

The StreamReader class allows us <strong>to</strong> access data from files.<br />

Useful methods of StreamReader:<br />

• ReadLine() returns one line as a string<br />

• Read() returns the ASCII for the next character and consumes it.<br />

• Peek() returns the ASCII for the next character without consuming it.<br />

When we hit the end of file Peek() returns –1 – this is useful <strong>to</strong> control a while loop<br />

(although not as useful as EOF would have been).<br />

A while loop <strong>to</strong> print the first non-space character of every line<br />

System.IO.StreamReader fh =<br />

new System.IO.StreamReader(@"..\..\Form1.cs");<br />

while (fh.Peek() != -1)<br />

{<br />

string ln = fh.ReadLine().TrimStart();<br />

if (ln.Length>0)<br />

Console.WriteLine(ln[0]);<br />

}<br />

MessageBox.Show("Done!");<br />

Notes:<br />

• StreamReader is in the System.IO namespace<br />

• ln.Length returns the length of a string<br />

• ln[0] gives the first character of the string ln. We get a run time error if the<br />

string is <strong>to</strong>o short.<br />

<strong>Intro</strong>duction <strong>to</strong> .NET<br />

Agilent .NET Course: C# Basics 10

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!