03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

686 ❘ APPENDIX A Solutions to Exercises<br />

}<br />

if (File.Exists("Notes.txt"))<br />

{<br />

// Read the file.<br />

using (StreamReader reader = new StreamReader("Notes.txt"))<br />

{<br />

notesTextBox.Text = reader.ReadToEnd();<br />

}<br />

}<br />

// Save the file.<br />

private void Form1_FormClosing(object sender, FormClosingEventArgs e)<br />

{<br />

using (StreamWriter writer = File.CreateText("Notes.txt"))<br />

{<br />

writer.Write(notesTextBox.Text);<br />

}<br />

}<br />

4. The WriteLine method adds a new line after the text it is writing into the file. When the program<br />

starts, it reads that new line as part of the text it displays in the TextBox. If the program<br />

uses WriteLine to save the text, it will write the original new line plus another one into the file.<br />

The result is the program adds another new line every time it starts and stops. (Try it and see.)<br />

You can avoid that by using the Write method instead of WriteLine.<br />

5. The LoadAndSaveFileWithPrompt example program uses the following Form_Closing<br />

event handler to prompt the user if the text file exists.<br />

// Save the file.<br />

private void Form1_FormClosing(object sender, FormClosingEventArgs e)<br />

{<br />

// See if the file exists.<br />

if (File.Exists("Notes.txt"))<br />

{<br />

// Prompt the user.<br />

DialogResult result =<br />

MessageBox.Show("The file exists. Do you want to overwrite it",<br />

"Overwrite",<br />

MessageBoxButtons.YesNoCancel,<br />

MessageBoxIcon.Question);<br />

// If the user clicked No, exit without saving.<br />

if (result == DialogResult.No) return;<br />

// If the user clicked Cancel, cancel.<br />

if (result == DialogResult.Cancel)<br />

{<br />

e.Cancel = true;<br />

return;<br />

}<br />

}<br />

// If the user clicked Yes, continue to overwrite the file.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!