2

我需要用新分数更新学生分数,但我无法将其写入学生当前分数的行。它只是删除整个文本。

Alex,letmein,0 David,qwerty1,0 John,password,0 Paul,lion,0 Luke,bennett,0 Ronald,Mcdonald,0 Erin,german,0 Laura,Scotland,0 Ross,extra,0 Alan,beverage,0

Try
 fileName = "C:\Documents and Settings\Student\Desktop\Task10\primary4.txt"
 Dim sWriter As New System.IO.StreamWriter(fileName) 
           index = lblPosition.Text
            sWriter.Write(username(index))
            sWriter.Write(",")
            sWriter.Write(password(index))
            sWriter.Write(",")
            sWriter.WriteLine(updatescore(position)
            sWriter.Close()
            MessageBox.Show("Writing file to disk")
            Me.Close()
     Catch ex As Exception
     MessageBox.Show(ex.Message)
End Try
4

2 回答 2

4

您不能更新文本文件中的特定行。您只能从头开始重写文本文件或附加到它。这不是你想要的。

您必须使用 File.ReadAllLines() 来获取带有文本文件中行的字符串 []。搜索要更新的数组中的特定元素。然后使用 File.WriteAllLines() 将其全部写回。

这当然很昂贵,但是您的文本文件很小。这是数据库引擎流行的主要原因。

于 2010-09-17T14:22:19.167 回答
1

我在这里看到至少一个额外的错误(异常会导致文件保持打开状态)。你应该这样做:

fileName = "C:\Documents and Settings\Student\Desktop\Task10\primary4.txt"
Dim sWriter As IO.StreamWriter
Try 
    sWriter = New IO.StreamWriter(fileName, True) 
    index = lblPosition.Text       
    sWriter.Write(username(index))
    sWriter.Write(",")
    sWriter.Write(password(index))
    sWriter.Write(",")
    sWriter.WriteLine(updatescore(position)
    MessageBox.Show("Writing file to disk")
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    sWriter.Close()
End Try
Me.Close()
于 2010-09-17T14:00:48.787 回答