15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

eading <strong>and</strong> Writing to files ❘ 785<br />

}<br />

InitializeComponent();<br />

}<br />

}<br />

private void button1_Click(object sender, EventArgs e)<br />

{<br />

textBox2.Text = File.ReadAllText(textBox1.Text);<br />

}<br />

code download ReadingFiles.sln<br />

In building this example, the first step is to add the using statement to bring in the System.IO namespace.<br />

From there, simply use the button1_Click event for the Send button on the form to populate the text<br />

box with what comes back from the file. You can now access the file’s contents by using the File.<br />

ReadAllText() method. As you can see, you can read files with a single statement. The ReadAllText()<br />

method opens the specified file, reads the contents, <strong>and</strong> then closes the file. The return value of the<br />

ReadAllText() method is a string containing the entire contents of the file specified. The result would be<br />

something similar to what is shown in Figure 29-7.<br />

figure 29-7<br />

The File.ReadAllText() signature shown in the preceding example is of the following construction:<br />

File.ReadAllText(FilePath);<br />

The other option is to also specify the encoding of the file being read:<br />

File.ReadAllText(FilePath, Encoding);<br />

Using this signature allows you to specify the encoding to use when opening <strong>and</strong> reading the contents of the<br />

file. Therefore, this means that you could do something like the following:<br />

File.ReadAllText(textBox1.Text, Encoding.ASCII);<br />

Some of the other options for opening <strong>and</strong> working with files include using the ReadAllBytes() <strong>and</strong><br />

the ReadAllLines() methods. The ReadAllBytes() method allows you to open a binary file <strong>and</strong> read<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!