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
---