我想将2行数字保存到txt文件中,我想在第一行添加1的整数,并在单击按钮时在第二行添加7。
因此,如果我单击按钮一次并打开txt文件,它将如下所示:
1
7
如果我点击它两次,它将如下所示:
2
14
我有以下代码,我知道这是错误的,因为它不断添加新行而不是编辑现有行。
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("stats.txt", True)
file.WriteLine(+1)
file.WriteLine(+7)
file.Close()
感谢您的帮助:)
答案 0 :(得分:3)
首先尝试从文件中读取行,将值转换为整数,然后重写到文件:
Dim Lines() As String = IO.File.ReadAllLines("stats.txt") 'Returns an array of string with one element for each line. In your case 2 elements in total
Dim FirstNewNumber As Integer = CInt(Lines(0)) + 1 'Cast the first element, aka the first line, to integer and add 1
Dim SecondNewNumber As Integer = CInt(Lines(1)) + 7 'Cast the second element, aka the second line, to integer and add 7
IO.File.WriteAllText("stats.txt", FirstNewNumber.ToString & _
vbNewLine & _
SecondNewNumber.ToString) 'Concatenate the string representations with & and insert a Newline character in between
始终记住为变量使用正确的数据类型。如果你对字符串使用+
运算符,它会在最好的情况下连接到字符串(aka "1" + "3"
将导致"13"
),并且在最坏的情况下根本不起作用。<登记/>
如果要使用算术计算,请使用整数等数值数据类型。并确保在项目中启用Option Strict
以通过强制正确的数据类型转换来避免错误。一开始可能看起来很麻烦但是相信我,这还不值得。
答案 1 :(得分:0)
'可以尝试这样的事情
Dim NewDocument As New List(Of String) 'List to save current and edited lines
Using sr As New StreamReader("stats.txt")
While Not sr.EndOfStream
Dim Line1 As String = sr.ReadLine
Dim Line2 As String = sr.ReadLine
Line1 = Line1 + 1
Line2 = Line2 + 7
NewDocument.Add(Line1)
NewDocument.Add(Line2)
End While
End Using
If System.IO.File.Exists("stats,txt") Then
System.IO.File.Delete(Filename)
End If
Using sw As New StreamWriter("stats.txt")
For Each line As String In HL7Doc
sw.WriteLine(line)
Next
End Using