Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Figure 9.6: In the Dungeon Editor, you can change the values of the screen elements.

The editor is designed along the same general lines as the game program but is designed for building and editing adventures rather than playing them. Each game is designed as a series of rooms. A room has a name, a description, and links to as many as four other rooms. You can type the name of the room and its description directly into the appropriate text boxes and can choose the other rooms from the drop−down list boxes. You can move between rooms in the editor with the Next and Prev buttons.

Trick I’ve found that the easiest way to write an adventure game with this system is to start by entering all the room names first. When I come back to edit the rooms, all the other room names are available in the list boxes. Creating all the connections then becomes a simple process. Finally, I flesh out the story by adding the descriptive text.

That the editor and the game engine use a similar interface is handy because it speeds up the learning curve. You can safely assume that a user interested in creating or editing an adventure has already played at least one, so having the elements in familiar places makes learning the editor easy for a user.

Reading and Writing Text Files

Before you can write a program as involved as the Adventure Kit, you need to understand how computers work with files. Information in variables is very powerful, but variables are essentially references to memory. Most computer memory is volatile, which means that it can store values only while power is flowing through the computer. If you want to store values that live beyond one session at the computer, you need to be able to store information in files on a disk drive. Perhaps the simplest kinds of files are plain text files, which store information in pure ASCII form on the disk. These files are easy to work with, and they are universal. Nearly every computer made can store and load text files. This is why most Internet standards are based on the plain text format.

241

C# uses the concept of streams to manage files. Essentially, a file can be thought of as a continuous stream of data. Some streams specialize in providing data to the program. These are known as input streams. Other streams are used to store information to a drive system. These output streams specialize in sending data from the program to the drive system.

Exploring the File IO Program

The File IO program, displayed in Figure 9.7, is an example of simple input and output (collectively called IO) using input and output streams. The user interface of File IO has one new feature. So far in this book, most text boxes have displayed only one line of information. It’s possible to set up a text box to show multiple lines of data, using the Multiline property. This is useful when you want to display more than one line in a textbox. In the FileIO program, I show the entire file in a textbox, so the Multiline property makes the text much easier to read.

Figure 9.7: The File IO program has a large text box and buttons for saving and loading the file.

Importing the IO Namespace

The input and output features of C# are stored in a namespace called System.IO. Figure 9.8 shows the help system’s entry point into the System.IO namespace. The System.IO namespace has very useful classes. Table 9.1 describes a few of the more important classes in this namespace.

242

Figure 9.8: The System.IO namespace includes classes for input and output streams. Table 9.1: Significant Classes in the System.IO Namespace

Class

Description

File

Features several methods for moving, copying, and testing a file (to see

 

whether it exists, when it was created, what kind of access it allows)

FileStream

The basic file class, allows the author to open, close, read, and write to

 

files, generally used for binary or random access data

StreamReader

A descendant of the FileStream class optimized for reading text−based

 

information from a file

StreamWriter

A descendant of the FileStream class optimized for writing text−based

 

information to a file

Path

Allows the programmer to create a valid file path from string data

Directory

Allows the programmer to create and manipulate directories

Many other classes are available in the System.IO namespace, but the classes in Table 9.1 are a good starting point.

Any of your programs that will use File IO must import the System.IO namespace. The line looks like this:

using System.IO;

Trick I didn’t show you the rest of the code for the startup of the File IO program because, except for the event handlers, it is the default code generated by the designer. You can see the program in its entirety on the CD−ROM.

Writing to a Stream

The interesting parts of the File IO program happen in the event handlers of the two buttons. The Save button has code for writing the contents of the text box to a file stream:

243

private void btnSave_Click(object sender, System.EventArgs e) { StreamWriter sw = new StreamWriter("practice.txt"); sw.Write(txtEdit.Text);

sw.Close();

} // end btnSave

The btnSave() method is an event handler, which is automatically called when the user clicks btnSave. The method begins by creating an instance of the StreamWriter class. StreamWriter is optimized to write text files. It has a number of constructors, but the easiest requires simply the name of the file you want to write. The method then uses the Write() method of sw to write the text from the text box to the file. The last line of the method uses the Close() method to close access to the file.

Trap Forgetting to close files is common. If you make this mistake, the program will continue to run, but you will encounter a file access error the next time you try to open the same file—because it’s already open. This can be an ugly bug to track down because your program crashes not where the error occurs but the next time the program tries to access the file. Be sure to close every file after you’re done accessing it.

Writing to a text file in this manner is extremely simple. If you want, you can also write data one line at a time to the file. The StreamWriter class supports many of the same methods as the Console class—such as Write() and WriteLine()—so it isn’t difficult to use.

Reading from a Stream

Reading text from a file is much like writing to a file, except that you create an instance of the StreamReader class instead of the StreamWriter class. The code for btnLoad() in File IO demonstrates how to read the text from the file:

private void btnLoad_Click(object sender, System.EventArgs e) { StreamReader sr = new StreamReader("practice.txt"); txtEdit.Text = sr.ReadToEnd();

sr.Close();

} // end btnLoad

As you can see from the code listing, the StreamReader class is very easy to use. To read data from the stream, you use reading methods. The ReadLine() method works just like the ReadLine() method in the Console class. It reads from the stream until it encounters an end−of−line character. Often, you want to read the entire text of a file into a variable. The ReadToEnd() method quickly reads the entire text file.

In the File IO program, I decided to predetermine a file name. Letting the user choose a file name would be better, but this can be a dangerous exercise because you never know what the user will type. In the Dialog Demo program later in this chapter, I’ll show you how to let the user choose a file. Meanwhile, turn your attention to menus.

In the Real World

The text methods outlined here work fine for small text files without a lot of fancy formatting. These methods become more cumbersome when you are working with a large amount of data or when the data has very specific organization. In those situations, you might want more specialized storage techniques, such as the object serialization strategy described in the Serialization Demo program later in this chapter, the XML strategies described in Chapter 10, “Basic XML: The Quiz Maker,” or the database strategies described in Chapter 11, “Databases and ADO.NET: The Spy Database.”

244

Соседние файлы в предмете Программирование на C++