Search code examples
vb.netstoring-data

Clearing a text file in Visual basic


This is the code i have so far, When a user gets a new high score it needs to clear the txt file and put the new high score in it or replace the number within the txt file. I am struggling to find a way to clear the file.

    ElseIf HighscoreDifficulty = "E" Then
        EasyHighScore = My.Computer.FileSystem.ReadAllText("EasyHighScore.txt")
        If CurrentScore > EasyHighScore Then
            NewHighScore.Visible = True
            file = My.Computer.FileSystem.OpenTextFileWriter("EasyHighScore.txt", True)
            file.WriteLine(CurrentScore)
            file.Close()
        Else
            NoNewHighScore.Visible = True
        End If

Thanks


Solution

  • Let's say that you want to keep the top five scores in the file. Assuming that the file always contains valid data, you could do that like this:

    Private Sub SaveHighScore(score As Integer)
        Const FILE_PATH = "file path here"
        Const MAX_SCORE_COUNT = 5
    
        'Read the lines of the file into a list of Integer values.
        Dim scores = File.ReadLines(FILE_PATH).
                          Select(Function(s) CInt(s)).
                          ToList()
    
        'Append the new score.
        scores.Add(score)
    
        'Sort the list in descending order.
        scores.Sort(Function(x, y) y.CompareTo(x))
    
        'Write up to the first five scores back tot he file.
        File.WriteAllLines(FILE_PATH,
                           scores.Take(MAX_SCORE_COUNT).
                                  Select(Function(i) i.ToString()))
    End Sub
    

    By adding the new score to the existing list, sorting and then writing out the first five, you automatically drop the lowest score. That means that there's never a need to actually check whether the new score is a high score or not.