Export (0) Print
Expand All

Walkthrough: Manipulating Files Using .NET Framework Methods

After completing this walkthrough, you will be able 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.

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, point to New, and then click Project.

    The New Project dialog box appears.

  2. In the Project Types pane, click Visual Basic Projects, and then click Windows Application in the Templates pane.
  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 Class. To add writing functionality:

  1. To open the Code Editor, select Code from the View menu.
  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
    
  3. Before writing to the file, you must create an instance of a StreamWriter class. Return to the Windows Forms Designer by selecting Designer from the View menu.
  4. Double-click the Submit button to create a click event handler for the button and then add the following code to it:
    Dim fw As StreamWriter
    
    Note   The Visual Studio Integrated Development Environment (IDE) returns to the Code Editor after the double-click and positions the cursor within the event handler where you should add the code.
  5. 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 doesn't 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
    
  6. To make sure that the user cannot submit a blank entry, add 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
    
  7. 8Because 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.ToString
    fw.Write(CStr(today))
    fw.Write(ControlChars.CrLf)
    
  8. Finally, attach code to clear the TextBox. Add the following code to the Clear button's Click event.
    Entry.Text = ""
    

To display the diary, additional functionality will display the latest entry in the DisplayEntry TextBox. Further refinement adds a ComboBox that displays various entries and from which a user can select an entry to display in the DisplayEntry TextBox. An instance of the StreamReader class will read 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.

Object Properties Value
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 ComboBox

  1. The PickEntries ComboBox will be used to display the dates on which a user submitted 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 to it:
    Dim fr As StreamReader
    Dim FileString As String
    FileString = ""
    Try
       fr = New 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
       fr.Close()
    End Try
    PickEntries.Enabled = True
    
  2. To test your code, press F5 to compile the application and click Show Entries. Click the dropdown 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 to it:
    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, submit an entry. Click Show Entries, select an entry from the ComboBox, and then click Display. The contents of the selected entry appears in the DisplayEntry TextBox.

Finally, additional functionality enables users to delete or modify an entry by using Delete Entry and Edit Entry buttons. Both buttons remain disabled unless an entry is being displayed.

  1. Add the controls in the following table to the form and set the corresponding values for their properties.
    Object Properties Value
    Button Name

    Text

    Enabled

    DeleteEntry

    Delete Entry

    False

    Button Name

    Text

    Enabled

    EditEntry

    Edit Entry

    False

    Button Name

    Text

    Enabled

    SubmitEdit

    Submit Edit

    False

  2. Add the following code to the Display button's click event, after DisplayEntry.Text = ReadString.
    DeleteEntry.enabled = True
    
  3. 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
    
  4. 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
    
  5. Create a Click event handler for the EditEntry button and add the following code to it:
    Entry.Text = DisplayEntry.Text
    SubmitEdit.Enabled = True
    
  6. Create a Click event handler for the SubmitEdit button and add the following code to it:
    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 Show Entries, select an entry, and then click Display. The entry displays in the DisplayEntry TextBox. Click Edit Entry. The entry displays in the Entry TextBox. Edit the entry in the Entry TextBox and click Submit Edit. Open the MyDiary.txt file to confirm your correction. Now select an entry and click Delete Entry. When the MsgBox requests confirmation, click OK. Close the application and open MyDiary.txt to confirm the deletion.

See Also

Choosing Among File I/O Options in Visual Basic .NET | StreamReader Class | StreamWriter Class | Accessing Files with FileSystemObject | Visual Basic Language Walkthroughs

Show:
© 2014 Microsoft