【问题标题】:How to delete the line at the end of the text file in vb.net?如何删除 vb.net 中文本文件末尾的行?
【发布时间】:2021-04-21 06:12:26
【问题描述】:

如何确保文件末尾没有多余的行?有点特别,我把一行分成三个地方,分别是17、90和120字节(总共:227字节)。我试图用Write替换WriteLine,这很好,但是之后我就不能写新行了! 我当前的代码:

 Dim bibliotheque As New article

        With bibliotheque
            .Title = TextBox1.Text
            .Name = TextBox2.Text
            .Charge = TextBox3.Text
        End With

        Dim fileName As String = "c:\essai.librairie"

        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(fileName, FileMode.Append)
            Using writer As StreamWriter = New StreamWriter(fs)

                writer.WriteLine(bibliotheque.Title.PadRight(17, " "c).ToString & bibliotheque.Name.PadRight(90, " "c).ToString & bibliotheque.Charge.PadRight(120, " "c).ToString)

                ListBox1.Items.Add(bibliotheque.Name)

            End Using

        Finally
            If fs IsNot Nothing Then
                fs.Dispose()
            End If
        End Try

【问题讨论】:

  • writer.WriteLine() writer.Write(bibliotheque.Title.... ?
  • 我的台词分成几个部分(那里,三个),在录音时,这是正确的。
  • 写完第一行之后,你可以使用类似 writer.Write(VbCr & (...)) 的东西。根据您用来打开文件的文本编辑器,您可能会改用 VbLf 或 VbCrLf。
  • 我正在使用记事本++和写字板:)
  • 没有空行。记事本或写字板等编辑器可让您将插入符号移到文件末尾之外,从而产生文本末尾有空行的错觉。实际上并不存在,如果没有该功能,添加更多文本行会很尴尬。

标签: vb.net filestream streamwriter


【解决方案1】:

您可以将WriteLine 替换为Write,使用布尔变量来了解您是否已添加第一行,如果已添加第一行,请使用WriteLine 添加回车符/换行符在添加内容之前使用空字符串,如下所示:

    Dim linesExist As Boolean = IO.File.ReadAllLines(fileName).Count > 0
    Try
                fs = New FileStream(fileName, FileMode.Append)
                Using writer As StreamWriter = New StreamWriter(fs)
                    If linesExist Then writer.WriteLine()
                    writer.Write(bibliotheque.Title.PadRight(17, " "c).ToString & bibliotheque.Name.PadRight(90, " "c).ToString & bibliotheque.Charge.PadRight(120, " "c).ToString)
                    ListBox1.Items.Add(bibliotheque.Name)
                End Using
    
            Finally
                If fs IsNot Nothing Then
                    fs.Dispose()
                End If
            End Try

很明显,File.ReadAllLines 可能会很慢,您可以使用更优化的方法来检测文件是否存在并包含内容,但它确实解决了手头的问题。

【讨论】:

  • 非常感谢 Spyros P。太好了! :) 克劳德。
【解决方案2】:
Dim fileName As String = "c:\essai.librairie"
Dim bt As New article With {
            .Title = TextBox1.Text,
            .Name = TextBox2.Text,
            .Charge = TextBox3.Text
    }

Using fs As New FileStream(fileName, FileMode.Append)
Using writer As New StreamWriter(fs)
    If fs.Length > 0 Then writer.WriteLine()
    writer.Write($"{bt.Title,-17}{bt.Name,-90}{bt.Charge,-120}")
End Using
End Using
ListBox1.Items.Add(bt.Name)

【讨论】:

  • 非常感谢乔尔·科霍恩。极好的。 :) 克劳德。
  • 两者都很好。这在这两种情况下都非常有效。
猜你喜欢
  • 1970-01-01
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2019-01-02
  • 2013-04-28
  • 2017-08-09
相关资源
最近更新 更多