Problem with StreamWriter... Writing onto a .txt file and saving it properly

Hekzdaddy 121 Reputation points
2021-05-01T03:54:49.78+00:00

Hello All, I have a simple program with several textbox's, I have an InputBox that sets the name and destination of the file that I am creating. My problem is the text entries are not being written. The file is created and sored in its location 'C:/temp/HectorBBB.txt and by name. But when I review the file it is blank.

Sub SaveDocument()

    ' Dim inputFile As StreamReader
    Dim strEmployeeData As String
    Dim outputFile As StreamWriter ' Object variable
    strEmployeeData = InputBox("enter a file name")

    Try
        'create the file
        outputFile = File.CreateText(strEmployeeData)
        'Write the TextBox to the file.
        outputFile.WriteLine(txtFirstName.Text)
        outputFile.WriteLine(txtMiddleName.Text)
        outputFile.WriteLine(txtLastName.Text)
        outputFile.WriteLine(txtEmployeeNumber.Text)
        outputFile.WriteLine(ComboDepartment.Text)
        outputFile.WriteLine(txtTelephone.Text)
        outputFile.WriteLine(txtExtension.Text)
        outputFile.WriteLine(txtEmail.Text)


        'Close the file.
        outputFile.Close()
        'update the isChnaged variable.
        ' blnIsChanged = False

    Catch ex As Exception
        'Error message for the file creation error.
        MessageBox.Show("Error creating the file.")
    End Try

End Sub

Please provide suggestions or advise, thank you.

Developer technologies | VB
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-05-01T10:36:09.01+00:00

    Hello,

    Try the following which provides a clean slate without dealing with user input for file name or data to write.

    If there is a failure it's reported back to the caller, otherwise it indicates success.

    Requires NuGet package ValueTuple (this package is include with .NET-5 Core but not in earlier Frameworks)

    Container to pass to write method

    Public Class Person  
        Public Property FirstName() As String  
        Public Property MiddleName() As String  
        Public Property LastName() As String  
        Public Property EmployeeNumber() As String  
        Public Property Department() As String  
        Public Property Telephone() As String  
        Public Property Extension() As String  
        Public Property Email() As String  
      
        Public Overrides Function ToString() As String  
            Return $"{FirstName} {LastName}"  
        End Function  
    End Class  
    

    File operations class:
    Which has an optional validate method

    Imports System.IO  
      
    Public Class FileOperations  
        ' requires NuGet package ValueTuple for return type  
        ' https://www.nuget.org/packages/System.ValueTuple/  
        Public Shared Function WriteData(sender As Person, fileName As String) As _  
            (Success As Boolean, Exception As Exception)  
      
            Try  
      
                If File.Exists(fileName) Then  
                    File.Delete(fileName)  
                End If  
      
                Using sw As New StreamWriter(fileName, False)  
      
                    sw.WriteLine(sender.FirstName)  
                    sw.WriteLine(sender.MiddleName)  
                    sw.WriteLine(sender.LastName)  
                    sw.WriteLine(sender.EmployeeNumber)  
                    sw.WriteLine(sender.Department)  
                    sw.WriteLine(sender.Telephone)  
                    sw.WriteLine(sender.Extension)  
                    sw.WriteLine(sender.Email)  
                End Using  
      
                Return (true, Nothing)  
      
            Catch ex As Exception  
      
                Return (True, ex)  
      
            End Try  
        End Function  
        Public Shared Function Validate(fileName As String) As Boolean  
            If File.Exists(fileName) Then  
                Return File.ReadAllLines(fileName).Length = 8  
            Else  
                Return False  
            End If  
        End Function  
    End Class  
    

    Form code:

    Public Class Form1  
      
        Private Sub WriteButton_Click(sender As Object, e As EventArgs) Handles WriteButton.Click  
      
            Dim person As New Person With {  
                .FirstName = "Line 1",  
                .MiddleName = "Line 2",  
                .LastName = "Line 3",  
                .EmployeeNumber = "Line 4",  
                .Department = "Line 5",  
                .Telephone = "Line 6",  
                .Extension = "Line 7",  
                .Email = "Line 8"  
            }  
      
            Dim fileName = "C:\temp\HectorBBB.txt"  
      
            Dim result = FileOperations.WriteData(person, fileName)  
      
            If result.Success Then  
                MessageBox.Show("Done")  
            Else  
                MessageBox.Show(result.Exception.Message)  
            End If  
      
        End Sub  
    End Class  
    

    ---
    93050-kpmvp1.png

    0 comments No comments

  2. JasonDaurison 116 Reputation points
    2021-05-24T19:54:40.843+00:00

    Hello, try using the following code:

         Dim strEmployeeData As String = InputBox("enter a file name")
         Dim outputFile As StreamWriter(strEmployeeData) ' Object variable
    
         Try
             'Write the TextBox to the file.
             outputFile.WriteLine(txtFirstName.Text)
             outputFile.WriteLine(txtMiddleName.Text)
             outputFile.WriteLine(txtLastName.Text)
             outputFile.WriteLine(txtEmployeeNumber.Text)
             outputFile.WriteLine(ComboDepartment.Text)
             outputFile.WriteLine(txtTelephone.Text)
             outputFile.WriteLine(txtExtension.Text)
             outputFile.WriteLine(txtEmail.Text)
             'Close the file.
             outputFile.Close()
             'update the isChnaged variable.
             ' blnIsChanged = False
         Catch ex As Exception
             'Error message for the file creation error.
             MessageBox.Show("Error creating the file.")
         End Try
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.