0

当使用 TextFieldParser 读取固定字段宽度的文本文件(17、90 和 120 个字符的 3 个字段,即 227 个字符)时,一旦我将最后一个文本框留空(TextBox4),就会出现错误。在我看来,这种情况正在发生,因为字段长度比预期的要短。

 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

在此处输入图像描述

'节省

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
4

0 回答 0