question

Hekzdaddy-3952 avatar image
0 Votes"
Hekzdaddy-3952 asked JasonDaurison-0792 edited

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

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.

dotnet-visual-basic
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

There's no obvious reason why the output file
should be empty. Provided of course that the
textboxes contained text when the file was written.

Ensure that you are looking at the right output file.
Pay special attention to the date/time stamp, to
ensure that you are looking at the right file.

  • Wayne

0 Votes 0 ·

Yeah I can see the file being created, and I was able to get it to write Line for each txtBox, I did that by adding the SubStatement to the formLoad event. However, I now have two inputBoxes the task is that I must write code in the formLoad event handler for an inputBox to store the file and assign a path. But if I remove the inputBox statement from the sub SaveFile() procedure, I end up with a variable that is being used before it has a value assigned to it. I will review it tomorrow and see if I can figure it out. Your feedback is appreciated.

0 Votes 0 ·
karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon edited

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



kpmvp1.png (3.5 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

JasonDaurison-0792 avatar image
0 Votes"
JasonDaurison-0792 answered JasonDaurison-0792 edited

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.