
Imports System.IO     'Appears at top of Code Editor

Public Class frmNames

  Private Sub btnAdd_Click(ByVal sender As System.Object,
                           ByVal e As System.EventArgs) Handles btnAdd.Click
    'Add a person's name to the file
    Dim person As String = txtName.Text
    If person <> "" Then
      If IsInFile(person) Then
        MessageBox.Show(person & " is already in the file.", "Alert")
      Else
        Dim sw As StreamWriter = File.AppendText("Names.txt")
        sw.WriteLine(person)
        sw.Close()
        MessageBox.Show(person & " added to file.", "Name Added")
        txtName.Clear()
        txtName.Focus()
      End If
    Else
      MessageBox.Show("You must enter a name.", "Information Incomplete")
    End If
  End Sub

  Private Sub btnDetermine_Click(ByVal sender As System.Object,
                                 ByVal e As System.EventArgs) Handles btnDetermine.Click
    'Determine if a person is in the file
    Dim person As String = txtName.Text
    If person <> "" Then
      If IsInFile(person) Then
        MessageBox.Show(person & " is in the file.", "Yes")
      Else
        MessageBox.Show(person & " is not in the file.", "No")
      End If
    Else
      MessageBox.Show("You must enter a name.", "Information Incomplete")
    End If
    txtName.Clear()
    txtName.Focus()
  End Sub

  Private Sub btnDelete_Click(ByVal sender As System.Object,
                              ByVal e As System.EventArgs) Handles btnDelete.Click
    'Remove the person in text box from the file
    Dim person As String = txtName.Text
    If person <> "" Then
      If IsInFile(person) Then
        'add code to remove
        Dim sr As StreamReader = File.OpenText("Names.txt")
        Dim sw As StreamWriter = File.CreateText("Temp.txt")
        Dim individual As String
        Do Until sr.EndOfStream
          individual = sr.ReadLine
          If individual <> person Then
            sw.WriteLine(individual)
          End If
        Loop
        sr.Close()
        sw.Close()
        File.Delete("Names.txt")
        File.Move("Temp.txt", "Names.txt")
        MessageBox.Show(person & " removed from file.", "Name Removed")
      Else
        MessageBox.Show(person & " is not in the file.", "Name Not Found")
      End If
    Else
      MessageBox.Show("You must enter a name.", "Information Incomplete")
    End If
    txtName.Clear()
    txtName.Focus()
  End Sub

  Function IsInFile(ByVal person As String) As Boolean
    'Determine if person is currently in a file named Names.txt
    If File.Exists("Names.txt") Then
      Dim sr As StreamReader = File.OpenText("Names.txt")
      Dim individual As String
      Do Until sr.EndOfStream
        individual = sr.ReadLine
        If individual = person Then
          sr.Close()
          Return True
        End If
      Loop
      sr.Close()
    End If
    Return False
  End Function

End Class
