Chapter 13 Exploring Text Files and String Processing 321
- Display the CloseToolStripMenuItem_Click event procedure, which is executed when the
Close menu command is clicked.
The event procedure looks like this:
txtNote.Text = "" 'clear text box
lblNote.Text = "Load a text file with the Open command."
CloseToolStripMenuItem.Enabled = False 'disable Close command
OpenToolStripMenuItem.Enabled = True 'enable Open command
The procedure clears the text box, updates the lblNote label, disables the Close
command, and enables the Open command.
Now you can use this simple program as a template for more advanced programs that
process text files. In the next section, you’ll learn how to type your own text into a text box
and how to save the text in the text box to a file on disk.
Writing Text Files
To create and write to a new text file on disk by using Visual Basic, you can use many of the
methods and keywords used in the last example. Creating new files on disk and saving data
to them is useful if you plan to generate custom reports or logs, save important calculations
or values, or create a special-purpose word processor or text editor. Here’s an overview of the
steps you’ll need to follow in the program:
- Get input from the user or perform mathematical calculations, or do both.
- Assign the results of your processing to one or more variables. For example, you could
assign the contents of a text box to a string variable. - Prompt the user for a path by using a SaveFileDialog control. You use the ShowDialog
method to display the dialog box. - Use the path received in the dialog box to open the file for output.
- Write one or more values to the open file.
- If necessary, close the file when you’re finished.
The WriteAllText Method
In the previous example, we used the My.Computer.FileSystem object with the ReadAllText
method. Not surprisingly, this object also includes the WriteAllText method. The WriteAllText
method writes text to a file. If a file does not exist, a new one is created. Here’s the syntax
you can use if you have a text box object on your form named txtNote (as in the last sample
program) and you plan to use a save file dialog object named SaveFileDialog1 to get the
name of the text file from the user:
SaveFileDialog1.Filter = "Text files (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
'copy text to disk