When using TextFieldParser to read a text file of fixed field width (3 fields of 17, 90 and 120 characters, i.e. 227 characters), I get an error as soon as I leave my last text box empty (TextBox4 ). This is happening, it seems to me, because the field length is shorter than expected.
Using Reader As New Microsoft.VisualBasic.FileIO.
TextFieldParser(OuvrirFichier, Encoding.UTF8)
Reader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader.SetFieldWidths(227)
Dim currentRow As String()
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
TextBox2.Text = currentField.Substring(0, 17)
TextBox1.Text = currentField.Substring(17, 90)
TextBox4.Text = currentField.Substring(107) ', 120))
Dim node As TreeNode = Me.TreeView1.Nodes(0)
TreeView1.Nodes(0).Nodes.Add(New TreeNode(TextBox1.Text))
ListBox2.Items.Add(TextBox1.Text)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("La ligne " & ex.Message &
" n'est pas valide et sera ignorée.")
End Try
End While
End Using
'Save
Dim fileName As String = OuvrirFichier
Dim bt As New article With {
.Title = TextBox2.Text,
.Name = TextBox1.Text,
.Charge = TextBox4.Text
}
Using fs As New FileStream(fileName, FileMode.Append)
Using writer As New StreamWriter(fs, Encoding.UTF8)
If fs.Length > 0 Then writer.WriteLine()
writer.Write($"{bt.Title,-17}{bt.Name,-90}{bt.Charge,-120}")
End Using
End Using