我已经在这里看过几次这个问题,但我似乎无法找到正确的答案。我目前有一个Windows表单应用程序,我用VB编写创建播放器配置文件(这是一个学校项目)。在“注册”页面上,我接收信息,并逐行读取每个字段逗号分隔符的.txt文件。这使得.txt看起来像这样:
Dan,Boyle,M,39,(707) 555-1234,555 S. West Street,18,D,R
Justin,Braun,M,27,(916) 555-1255,858 W. South St,5,D,L
我向右边开了一行,然后调用它就好了但我需要为我的项目做的就是编辑一个播放器配置文件。到目前为止我发现的最好的方法是重写整条线,这是我设法做到的。但我无法弄清楚的是如何删除当前行并替换。
Dim FileString As String = "MasterRoster.txt"
Dim index As Integer = Home.cbPlayerLookUp.SelectedIndex
Dim playerInfo() As String = File.ReadAllLines(FileString)
Dim FieldString() As String
Dim RecordString As String = ""
If Not playerInfo.Length < index Then
FieldString = playerInfo(index).Split(","c)
'Update Player stats)
If CInt(FieldString(16)) = index Then
FieldString(12) = CStr(CInt(FieldString(12)) + CInt(txtGoals.Text))
FieldString(13) = CStr(CInt(FieldString(13)) + CInt(txtAssists.Text))
FieldString(14) = CStr(CInt(FieldString(14)) + CInt(txtPIM.Text))
FieldString(15) = CStr(CInt(FieldString(15)) + CInt(txtGames.Text))
'(FirstName0, LastName1, Gender2, Age3, Phone4, Address5, Experience6, Position7, Handedness8, Team9, Jersey#10, imgPath11, Goals12, Assists13, PIM14, Total Games15, playerID Number16)
RecordString = FieldString(0) & "," & FieldString(1) & "," & FieldString(2) & "," & FieldString(3) & "," & FieldString(4) & "," & FieldString(5) &
"," & FieldString(6) & "," & FieldString(7) & "," & FieldString(8) & "," & FieldString(9) & "," & FieldString(10) & "," & FieldString(11) & "," & FieldString(12) & "," &
FieldString(13) & "," & FieldString(14) & "," & FieldString(15) & "," & FieldString(16) & vbNewLine
End If
My.Computer.FileSystem.WriteAllText(FileString, RecordString, True)
End If
这将在我的.txt文件“MasterRoster.txt”的底部添加一个新行,最后更新的信息,但旧的仍在那里。我怎样才能代替旧线?
答案 0 :(得分:0)
由于您正在将整个文件读入内存,因此使用类来表示信息可以让您为每个字段添加有意义的名称。(您还记得每个字段代表从现在开始一两年的内容吗?)一种方法该数据的集合位于DataTable中,该DataTable非常易于与DataGridView一起使用,以显示用于读取和编辑的数据。另一种选择是使用.xml文本格式而不是.csv文本格式。这样可以更容易地读取和写入文件,因为DataTable具有为此设计的方法。
在任何情况下,编辑特定记录都需要覆盖或重写文件,除非您想要向后退一步并使用旧的遗留方法FileOpen,FileGet和FilePut。