views:

82

answers:

2

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
A: 

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()
Joel Coehoorn
Name 'sWriter' is not declared?
Alex
Sure it is - one the line above the Try. Don't forget that part.
Joel Coehoorn
+2  A: 

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.

Hans Passant
You can write to the middle of a text file. You just can't change the length of the line without re-writing everything in the file after it.
Joel Coehoorn
Finding the *position* of the line is quite a challenge. StreamReader/Writer isn't going to help (no Position, no Seek), dealing with line endings and the BOM yourself is no fun.
Hans Passant