I've been struggling with this for a few hours, and I post this question with reluctance.
I am assigned to make a program that reads a name, saves it to a text box and writes the name and number to a text file upon the forms closing. Upon the form's loading, it should read the name and number from 2 text files and display that info. The number is automatically generated and the next customer number is read from a text file.
However, I am having a hard time with the streamwriter: I am particularly getting an error when I try to write to outFile2: NullReferenceError for outFile2.
Basically outFile2 doesn't open the file or append the output file. How can I get this program to work without trying to figure out why every method of read/write buffer crashes on me?
Private inFile1, inFile2 As IO.StreamReader
Private outFile1, outFile2 As IO.StreamWriter
Private customerNum As Integer = 1
Private customerName As String
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim tempStr As String
If IO.File.Exists("CustomerNumbers.txt") = False Then
outFile1 = IO.File.CreateText("CustomerNumbers.txt")
inFile1 = IO.File.OpenText("CustomerNumbers.txt")
Else
inFile1 = IO.File.OpenText("CustomerNumbers.txt")
outFile1 = IO.File.AppendText("CustomerNumbers.txt")
End If
If IO.File.Exists("CustomerNames.txt") = False Then
outFile2 = IO.File.CreateText("CustomerNames.txt")
inFile2 = IO.File.OpenText("CustomerNames.txt")
Else
inFile2 = IO.File.OpenText("CustomerNames.txt")
outFile2 = IO.File.AppendText("CustomerNames.txt")
End If
If inFile1.Read = Nothing Then
customerNum = 1
txtList.Text = customerNum
End If
Do While inFile1.Peek() <> -1
tempStr = inFile1.ReadLine
customerNum = tempStr
Loop
Do While inFile2.Peek() <> -1
customerName = inFile2.ReadLine().ToString
txtList.Text += customerName & vbCrLf
Loop
lblNumber.Text = customerNum
inFile1.Close()
inFile2.Close()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
outFile1.WriteLine(customerNum)
outFile1.Close()
outFile2.Close()
Me.Close()
End Sub
Private Sub btnSaveCustomer_Click(sender As Object, e As EventArgs) Handles btnSaveCustomer.Click
If (txtCustomerName.Text <> Nothing) Then
txtList.Text += customerNum & " " & txtCustomerName.Text & vbCrLf
//error thrown here usually
outFile2.WriteLine(customerNum.ToString & " " & txtCustomerName.Text.ToString)
customerNum = customerNum + 1
lblNumber.Text = customerNum
txtCustomerName.Clear()
txtCustomerName.Focus()
End If
End Sub
Paste from Comment:
If IO.File.Exists("CustomerNames.txt") = False Then
Dim outFile1, outFile2 As IO.StreamWriter
outFile2 = IO.File.CreateText("CustomerNames.txt")
Using outFile2 = IO.File.AppendText("CustomerNames.txt")
outFile2.WriteLine(customerNum.ToString & " " & txtCustomerName.Text.ToString)
End Using
End I