在 Visual basic 中清除文本文件

Clearing a text file in Visual basic

这是我目前的代码,当用户获得新的高分时,它需要清除 txt 文件并将新的高分放入其中或替换 txt 文件中的数字。我正在努力寻找清除文件的方法。

    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

谢谢

假设您要在文件中保留前五名的分数。假设文件始终包含有效数据,您可以这样做:

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

通过将新分数添加到现有列表、排序然后写出前五个分数,您会自动删除最低分数。这意味着永远不需要实际检查新分数是否为高分。