Write Text In A Already Existing Text File VB.NET

joao picture joao · Apr 7, 2012 · Viewed 35k times · Source

I've been developing a arcade game, and as every good arcade game, it has an incorporated scoreboard so that players can see who scored better. My problem is that everytime it enters a new scoreline, it deletes all the previous lines in the text file. The code I've been using is the following:

    If player1 > 25 Then

        objReader.Close()
        MsgBox("O " + jogador1 + " ganhou.")
        tab1.Enabled = False

        Dim wrtScore As String = "C:\Documents and Settings\Joao\My Documents\Visual Studio 2010\Projects\flaghunter\flaghunter\deposito\scores.txt"
        Dim objWriter As New System.IO.StreamWriter(wrtScore)

        wrtScore = wrtScore.Trim()

        objWriter.WriteLine(jogador1 + " " + Str(player1))

        objWriter.Close()


    End If

Thank you for your attention and any help.

Answer

Icarus picture Icarus · Apr 7, 2012

Use File.AppendText instead:

    // This text is always added, making the file longer over time
    // if it is not deleted.
 Using sw As StreamWriter = File.AppendText(path)
        sw.WriteLine("This")
        sw.WriteLine("is Extra")
        sw.WriteLine("Text")
 End Using

This will create the file if it doesn't exist the first time and append the text if the file already exists