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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

424 ❘ CHAPTER 18 Streams<br />

Exercises<br />

1. The WriteIntoMemoryStream example program uses Dispose statements to free its<br />

MemoryStream, BinaryWriter, and BinaryReader objects. Rewrite the code with using<br />

statements instead. Which version is easier to read<br />

2. What happens if you don’t dispose of a stream attached to a file A memory stream Which<br />

case is worse<br />

3. Write a program that reads and uses File class methods and streams to save and restore<br />

some text when it starts and stops. When it starts, the program should open a text file (if<br />

it exists) and display its contents in a multiline TextBox. When it is closing, the program<br />

should save the TextBox’s contents into the file, overwriting its previous contents.<br />

4. One way a solution to Exercise 3 can save text is by using a StreamWriter’s Write or<br />

WriteLine method. Which of those methods should you use and why<br />

5. Modify the program you wrote for Exercise 3 to prompt the user to ask if it should overwrite<br />

the file. Take appropriate action when the user clicks Yes, No, or Cancel.<br />

6. Write a program that indicates whether the lines in a file are in alphabetical order. Assume<br />

the file is huge, so the program must read the file one line at a time and compare each line<br />

to the previous one. (That way it needs to store only two lines of text at any given time. It<br />

can also stop if it ever finds two lines out of order.)<br />

7. Modify the program you wrote for Exercise 14-8 so that it writes the primes into the file<br />

Primes.txt in addition to displaying them in a ListBox.<br />

8. Modify the program you wrote for Exercise 7 so that it saves the primes in a binary file<br />

named Primes.dat. When the program starts, it should read that file (if it exists) and<br />

display the saved values in the ListBox. (Hint: The BinaryReader class doesn’t have<br />

an EndOfStream property. To let it know how many values to read, save the number of<br />

primes at the beginning of the file.)<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!