claudebl
claudebl

Reputation: 75

How to delete the line at the end of the text file in vb.net?

How do I ensure that I don't have an extra line at the end of the file? It's a bit special, I divide the line into three places which are respectively 17, 90 and 120 bytes (total: 227 bytes). I tried to replace WriteLine with Write, that's fine, but after that I can't write new lines! My current code:

 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

Upvotes: 0

Views: 374

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

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)

Upvotes: 1

Spyros P.
Spyros P.

Reputation: 296

You can replace WriteLine with Write, use a boolean variable to know if you have already added the first line and if the first line has been added, add just the carriage return/line feed using a WriteLine with an empty string, before adding content, like that:

    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

Obviously, File.ReadAllLines might be slow and you can use more optimized methods to detect if the file exists and has content, but it does solve the problem at hand.

Upvotes: 1

Related Questions