在已经存在的文本文件中写入文本 VB.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10056584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:02:43  来源:igfitidea点击:

Write Text In A Already Existing Text File VB.NET

vb.nettextlinesstreamwriter

提问by joao

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.

感谢您的关注和任何帮助。

回答by Icarus

Use File.AppendTextinstead:

改用File.AppendText

    // 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

如果第一次不存在,这将创建文件,如果文件已经存在,则附加文本

回答by Nguy?n Hoàng Gia

Dim objWriter As New System.IO.StreamWriter(wrtScore, TRUE)to append to file :D

Dim objWriter As New System.IO.StreamWriter(wrtScore, TRUE)附加到文件:D

回答by Corum Ian Halligan

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()