Pergunta

I need to update the students score with a new score but I cant get it to write to the line that the students current score it at. It just deletes the whole text.

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
Foi útil?

Solução

You cannot update a specific line in a text file. You can only rewrite a text file from scratch or append to it. Which is not what you want here.

You have to use File.ReadAllLines() to get a string[] with the lines in the text file. Search the specific element in the array that you want to update. Then write it all back with File.WriteAllLines().

This is expensive of course, but your text file is small. This is the primary reason why database engines are popular.

Outras dicas

I see at least one additional bug in here (an exception would result in leaving the file open). You should do something like this instead:

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()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top