gpt4 book ai didi

vb.net - 在按钮上编辑 txt 文件单击 vb.net

转载 作者:行者123 更新时间:2023-12-01 23:54:06 25 4
gpt4 key购买 nike

我想将 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()

感谢您的帮助:)

最佳答案

首先尝试从文件中读取行,将值转换为整数,然后重写到文件中:

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

永远记得为变量使用正确的数据类型。如果您在字符串上使用 + 运算符,在最好的情况下,它将连接到字符串(又名 "1"+ "3" 将导致 "13 "),在最坏的情况下根本无法工作。
如果要使用算术计算,请使用整数等数字数据类型。并确保在您的项目中启用 Option Strict 以通过强制正确的数据类型转换来避免错误。起初这似乎很麻烦,但请相信我,这是非常值得的。

关于vb.net - 在按钮上编辑 txt 文件单击 vb.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25025387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com