Walkthrough: Manipulating Files by Using .NET Framework Methods (Visual Basic)

This walkthrough demonstrates how to open and read a file using the StreamReader class, check to see if a file is being accessed, search for a string within a file read with an instance of the StreamReader class, and write to a file using the StreamWriter class.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Creating the Application

Start Visual Studio and begin the project by creating a form that the user can use to write to the designated file.

To create the project

  1. On the File menu, select New Project.

  2. In the New Project pane, click Windows Application.

  3. In the Name box type MyDiary and click OK.

    Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

  4. Add the controls in the following table to the form and set the corresponding values for their properties.

Object

Properties

Value

Button

Name

Text

Submit

Submit Entry

Button

Name

Text

Clear

Clear Entry

TextBox

Name

Text

Multiline

Entry

Please enter something.

False

Writing to the File

To add the ability to write to a file via the application, use the StreamWriter class. StreamWriter is designed for character output in a particular encoding, whereas the Stream class is designed for byte input and output. Use StreamWriter for writing lines of information to a standard text file. For more information on the StreamWriter class, see StreamWriter.

To add writing functionality

  1. From the View menu, choose Code to open the Code Editor.

  2. Because the application references the System.IO namespace, add the following statements at the very beginning of your code, before the class declaration for the form, which begins Public Class Form1.

    Imports System
    Imports System.IO
    

    Before writing to the file, you must create an instance of a StreamWriter class.

  3. From the View menu, choose Designer to return to the Windows Forms Designer. Double-click the Submit button to create a Click event handler for the button, and then add the following code.

    Dim fw As StreamWriter
    

Note

The Visual Studio Integrated Development Environment (IDE) will return to the Code Editor and position the insertion point within the event handler where you should add the code.

  1. To write to the file, use the Write method of the StreamWriter class. Add the following code directly after Dim fw As StreamWriter. You do not need to worry that an exception will be thrown if the file is not found, because it will be created if it does not already exist.

    Dim ReadString As String 
    Try 
        'Pass the file path and name to the StreamWriter constructor. 
        'Indicate that Append is True, so file will not be overwritten.
        fw = New StreamWriter("C:\MyDiary.txt", True)
        ReadString = Entry.Text
        fw.WriteLine(ReadString)
    Finally 
        'Close the file.
        fw.Close()
    End Try
    
  2. Make sure that the user cannot submit a blank entry by adding the following code directly after Dim ReadString As String.

    If (Entry.Text = "" Or Entry.Text = "Please enter something.") Then
        Entry.Text = "Please enter something." 
        Return 
    End If
    
  3. Because this is a diary, the user will want to assign a date to each entry. Insert the following code after fw = New StreamWriter("C:\MyDiary.txt", True) to set the variable Today to the current date.

    Dim Today As DateTime
    Today = Now
    fw.Write(CStr(Today))
    fw.Write(ControlChars.CrLf)
    
  4. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.

    Entry.Text = ""
    

Adding Display Features to the Diary

In this section, you add a feature that displays the latest entry in the DisplayEntryTextBox. You can also add a ComboBox that displays various entries and from which a user can select an entry to display in the DisplayEntryTextBox. An instance of the StreamReader class reads from MyDiary.txt. Like the StreamWriter class, StreamReader is intended for use with text files.

For this section of the walkthrough, add the controls in the following table to the form and set the corresponding values for their properties.

Control

Properties

Values

TextBox

Name

Visible

Size

Multiline

DisplayEntry

False

120,60

True

Button

Name

Text

Display

Display

Button

Name

Text

GetEntries

Get Entries

ComboBox

Name

Text

Enabled

PickEntries

Select an Entry

False

To populate the combo box

  1. The PickEntriesComboBox is used to display the dates on which a user submits each entry, so the user can select an entry from a specific date. Create a Click event handler to the GetEntries button and add the following code.

    Dim fr As StreamReader = Nothing 
    Dim FileString As String
    FileString = "" 
    Try
        fr = New System.IO.StreamReader("C:\MyDiary.txt")
        PickEntries.Items.Clear()
        PickEntries.Enabled = True 
        Do
            FileString = fr.ReadLine
            If IsDate(FileString) Then
                PickEntries.Items.Add(FileString)
            End If 
        Loop Until (FileString Is Nothing)
    Finally 
        If fr IsNot Nothing Then
            fr.Close()
        End If 
    End Try
    PickEntries.Enabled = True
    
  2. To test your code, press F5 to compile the application, and then click Get Entries. Click the drop-down arrow in the ComboBox to display the entry dates.

To choose and display individual entries

  1. Create a Click event handler for the Display button and add the following code.

    Dim fr As StreamReader
    Dim ReadString As String 
    'Make sure ReadString begins empty.
    ReadString = "" 
    Dim FileString As String
    fr = New StreamReader("C:\MyDiary.txt")
    'If no entry has been selected, show the whole file. 
    If PickEntries.Enabled = False Or PickEntries.SelectedText Is Nothing Then 
        Do 
            'Read a line from the file into FileString.
            FileString = fr.ReadLine
            'add it to ReadString
            ReadString = ReadString & ControlChars.CrLf & FileString
        Loop Until (FileString = Nothing)
    Else 
        'An entry has been selected, find the line that matches. 
        Do
    
            FileString = fr.ReadLine
        Loop Until FileString = CStr(PickEntries.SelectedItem)
        FileString = CStr(PickEntries.SelectedItem) & ControlChars.CrLf
        ReadString = FileString & fr.ReadLine
    
        'Read from the file until EOF or another Date is found. 
        Do Until ((fr.Peek < 0) Or (IsDate(fr.ReadLine)))
            ReadString = ReadString & fr.ReadLine
        Loop 
    End If
    fr.Close()
    DisplayEntry.Visible = True
    DisplayEntry.Text = ReadString
    
  2. To test your code, press F5 to compile the application, and then submit an entry. Click Get Entries, select an entry from the ComboBox, and then click Display. The contents of the selected entry appear in the DisplayEntryTextBox.

Enabling Users to Delete or Modify Entries

Finally, you can include additional functionality enables users to delete or modify an entry by using DeleteEntry and EditEntry buttons. Both buttons remain disabled unless an entry is displayed.

Add the controls in the following table to the form and set the corresponding values for their properties.

Control

Properties

Values

Button

Name

Text

Enabled

DeleteEntry

Delete Entry

False

Button

Name

Text

Enabled

EditEntry

Edit Entry

False

Button

Name

Text

Enabled

SubmitEdit

Submit Edit

False

To enable deletion and modification of entries

  1. Add the following code to the Display button's Click event, after DisplayEntry.Text = ReadString.

    DeleteEntry.enabled = True
    
  2. Create a Click event handler for the DeleteEntry button and add the following code.

    Dim fr As StreamReader
    Dim ReadString As String 
    Dim WriteString As String 
    Dim ConfirmDelete As MsgBoxResult
    fr = New StreamReader("C:\MyDiary.txt")
    ReadString = fr.ReadLine
    ' Read through the textfile 
    Do Until (fr.Peek < 0)
        ReadString = ReadString & vbCrLf & fr.ReadLine
    Loop
    WriteString = Replace(ReadString, DisplayEntry.Text, "")
    fr.Close()
    ' Check to make sure the user wishes to delete the entry
    ConfirmDelete = MsgBox("Do you really wish to delete this entry?",
      MsgBoxStyle.OKCancel)
    If ConfirmDelete = MsgBoxResult.OK Then
        File.Delete("C:\MyDiary.txt")
        Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
        fw.WriteLine(WriteString)
        fw.Close()
        ' Reset controls on the form
        DisplayEntry.Text = ""
        PickEntries.Text = ""
        PickEntries.Items.Clear()
        PickEntries.Enabled = False
        DeleteEntry.Enabled = False 
    End If
    
  3. When a user displays an entry, the EditEntry button becomes enabled. Add the following code to the Click event of the Display button after DisplayEntry.Text = ReadString.

    EditEntry.Enabled = True
    
  4. Create a Click event handler for the EditEntry button and add the following code.

    Entry.Text = DisplayEntry.Text
    SubmitEdit.Enabled = True
    
  5. Create a Click event handler for the SubmitEdit button and add the following code

    Dim fr As StreamReader
    Dim ReadString As String 
    Dim WriteString As String 
    If Entry.Text = "" Then
        MsgBox("Use Delete to Delete an Entry")
        Return 
    End If
    fr = New StreamReader("C:\MyDiary.txt")
    ReadString = fr.ReadLine
    Do Until (fr.Peek < 0)
        ReadString = ReadString & vbCrLf & fr.ReadLine
    Loop
    WriteString = Replace(ReadString, DisplayEntry.Text, Entry.Text)
    fr.Close()
    File.Delete("C:\MyDiary.txt")
    Dim fw As StreamWriter = File.CreateText("C:\MyDiary.txt")
    fw.WriteLine(WriteString)
    fw.Close()
    DisplayEntry.Text = Entry.Text
    Entry.Text = ""
    EditEntry.Enabled = False
    SubmitEdit.Enabled = False
    

To test your code, press F5 to compile the application. Click Get Entries, select an entry, and then click Display. The entry appears in the DisplayEntryTextBox. Click Edit Entry. The entry appears in the EntryTextBox. Edit the entry in the EntryTextBox and click Submit Edit. Open the MyDiary.txt file to confirm your correction. Now select an entry and click Delete Entry. When the MessageBox requests confirmation, click OK. Close the application and open MyDiary.txt to confirm the deletion.

See Also

Reference

StreamReader

StreamWriter

Other Resources

Visual Basic Language Walkthroughs