问题
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.
回答1:
Dim objWriter As New System.IO.StreamWriter(wrtScore, TRUE)
to append to file :D
回答2:
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
回答3:
Append to beginning of file, try load contents then overwrite file and drop contents at bottom. Something Like:
Dim sr as New StreamReader("path/to/file.ext")
Dim text as String = sr.ReadToEnd()
sr.Close()
Dim sw as New StreamWriter("path/to/file.ext")
sw.WriteLine("New stuff")
sw.WriteLine("More New Stuff")
sw.WriteLine(text) ' Add original content back
sw.Close()
来源:https://stackoverflow.com/questions/10056584/write-text-in-a-already-existing-text-file-vb-net