University of Alaska system



File Input and Output

File I/O (Input and Output) is covered in chapter 9.

Reading Data from a Text File

If you have stored data in a text file, using a program such as Notepad, you can also read it with C#. Reading from a text file is useful to load the program with large amounts of data that would otherwise be tedious to type.

Data can be stored in files and accessed with a StreamReader object.

The steps to use the StreamReader object are as follows:

1. Add the following to the top of your class:

using System.IO;

This tells C# that you want to use the code defined in the System.IO namespace, which includes ways to read and write to files.

2. Write a statement of the form

StreamReader readerVar;

A StreamReader is an object from the Input/Output class that can read a stream of characters coming from a disk or coming over the Internet. The statement declares the variable readerVar to be of type StreamReader.

3. Write a statement of the form

readerVar = new StreamReader(filepath);

where filepath identifies the file to be read. This statement establishes a communications link between the computer and the disk drive for reading data from the disk. Data then can be input from the specified file and assigned to variables in the program. This assignment statement is said to “open the file for input.”

Just as with other variables, the declaration and assignment statements in Steps

1 and 2 can be combined into the single statement:

StreamReader readerVar = new StreamReader(filepath);

If the filepath contains the \ character, don’t forget that this is the same as the escape character, so you need two slashes \\ to represent a single slash.

4. Read items of data in order, one at a time, from the file with the ReadLine method.

Each datum is retrieved as a string. A statement of the form

strVar = readerVar.ReadLine();

causes the program to look in the file for the next unread line of data and assign it to the variable strVar. The data can be assigned to a numeric variable if it is converted to a numeric type with the usual statements, e.g.:

intVar = Convert.ToInt32(readerVar.ReadLine());

Note: If all the data in a file have been read by ReadLine statements and another item is requested by a ReadLine statement, the item retrieved will have the value null.

5. If you want to check to see if we have read everything in the file use the following:

readerVar.EndOfStream

This property returns false if there is still data to be read, and true if we have read everything and are now at the end of thefile.

6. After the desired items have been read from the file, terminate the communications link set in Step 2 with the statement

readerVar.Close();

As an example, consider a file of university employees that is stored in the file C:\PEOPLE.TXT and it contains the following:

Cotty, Manny

English

40205

Kick, Anita

Dance

45495

Guini, Lynn

Culinary Arts

67300

DeBanque, Robin

English

38500

Wright, Eaton

Culinary Arts

75800

Bugg, June

Biology

95300

This says that Manny Cotty is in the English department and makes $40,205 a year.

Anita Kick is in the Dance department and makes $45,495 a year.

Etc.

Let’s say we want a program that outputs the names and salaries of people in the English department. Here is a program that reads in three lines of data at a time, checks if the department is English, and if so outputs the name and salary:

System.IO.StreamReader rv = new

System.IO.StreamReader("c:\\people.txt");

while (!rv.EndOfStream)

{

string name = rv.ReadLine();

string department = rv.ReadLine();

int salary = Convert.ToInt32(rv.ReadLine());

if (department=="English")

{

Console.WriteLine(name + " makes " + salary);

}

}

rv.Close();

The output is:

Cotty, Manny makes 40205

DeBanque, Robin makes 38500

Here is another example that reads in words from a dictionary file to solve this word puzzle: "Name a common word, besides tremendous, stupendous and horrendous, that ends in dous."

We can solve this problem by loading up a file of words and checking each one to see if:

1) It is more than 4 letters long

2) The word contains “dous” at the end

Assume we have a file of English words located at C:\WORDS.TXT

System.IO.StreamReader rv = new

System.IO.StreamReader("c:\\words.txt");

while (!rv.EndOfStream)

{

string word = rv.ReadLine();

if (word.Length > 4)

{

if (word.EndsWith("dous"))

{

Console.WriteLine(word);

}

}

}

rv.Close();

Writing To Sequential Text Files

Here we’ll cover just the very basics of how to write and create a text file from your program.

Creating a text file is a lot like opening a file for reading, except we open it for creation instead. The steps to create a new text file and write data to it are:

1. Add using System.IO; to the top of the program.

2. Create a StreamWriter object:

StreamWriter swriter = new StreamWriter(filepath);

This will create a blank file with the given pathname. If the file already exists, it will be destroyed! (There is a separate constructor, new StreamWriter(filepath, true) that will append to an existing file.

If we don’t specify a full path then by default the file is placed in the current working directory (the bin directory of the project, if running from visual studio)

3. To place data in the file, use WriteLine, as we have used to write data to the console, except precede it by the Stream Writer variable:

swriter.WriteLine(data);

4. When you are done recording data to the file, close it:

swriter.Close();

The close statement breaks the link with the file on disk and frees up space in memory. Note that if you write data to a file and try to look at it with a text editor, the data may not actually be saved to disk until the file is closed.

Here is an example that writes “hello there” and the number 42 to disk:

StreamWriter swriter = new StreamWriter("c:\\homeworks\\output.txt");

swriter.WriteLine("hello there!");

swriter.WriteLine(42);

swriter.Close();

In an ideal setting, any file input/output should be enclosed inside a try/catch block in case there are File I/O errors (e.g. you don’t have file permissions, the disk is full, etc.)

Trivia Game File Example

Let’s modify our trivia game so it loads its questions from a file instead of manually entering them into the Form_Load event. This will make it much more scalable and easier to maintain. Here is the old code:

private void Form1_Load(object sender, EventArgs e)

{

int numQuestions = 5; // Later we will read from a file

trivia = new Trivia[numQuestions];

Trivia item = new Trivia("The possession of more than two sets of chromosomes is termed?", "polyploidy", 2);

trivia[0] = item;

item = new Trivia("Age of Amelia Earhart when she disappeared.",

"39", 3);

trivia[1] = item;

// We can directly set the reference in the array

trivia[2] = new Trivia("Actor whose real name was Marion Morrison", "John Wayne", 1);

trivia[3] = new Trivia("This psychologist taught pigeons how to play ping pong", "B.F. Skinner", 2);

trivia[4] = new Trivia("I am the geometric figure most like a lost parrot", "polygon", 3);

ShowQuestion();

}

First, let’s create a file named “trivia.txt” that contains the trivia question, answer, and value. The first line contains the number of questions in the file. This will help us when we read the data in so we know how big to make the arrays. Here is the contents of the file, which I created in the bin\debug directory which is the default location for Visual Studio:

5

The possession of more than two sets of chromosomes is termed?

polyploidy

2

Age of Amelia Earhart when she disappeared.

39

3

Actor whose real name was Marion Morrison.

John Wayne

1

This psychologist taught pigeons how to play ping pong.

B.F. Skinner

2

I am the geometric figure most like a lost parrot.

polygon

3

Once again, the first line indicates how many questions are in the file. The rest are the question, answer, and point value.

Our program now opens the file and reads in the first line. This number is converted to an int and used to allocate the arrays. We then loop through the rest of the file, reading each question/answer/value into the appropriate array:

private void Form1_Load(object sender, EventArgs e)

{

int numQuestions;

// Read the trivia.txt file from the default bin\debug folder

StreamReader triviaFile = new StreamReader("trivia.txt");

// Read number of questions, which is the first line in the file

numQuestions = Convert.ToInt32(triviaFile.ReadLine());

trivia = new Trivia[numQuestions];

// Load questions in from the file

for (int i = 0; i < numQuestions; i++)

{

string q = triviaFile.ReadLine();

string a = triviaFile.ReadLine();

int v = Convert.ToInt32(triviaFile.ReadLine());

trivia[i] = new Trivia(q, a, v);

}

triviaFile.Close(); // Close the file when done

ShowQuestion();

}

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download