Using System.IO.StreamWriter to write another line

12,061

Solution 1

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.

Solution 2

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()
Share:
12,061
Alex
Author by

Alex

Updated on July 21, 2022

Comments

  • Alex
    Alex almost 2 years

    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
    
    • Alex
      Alex over 13 years
      I have about 260 lines of code that go with this if it would help anyone?
  • Alex
    Alex over 13 years
    Name 'sWriter' is not declared?
  • Joel Coehoorn
    Joel Coehoorn over 13 years
    Sure it is - one the line above the Try. Don't forget that part.
  • Joel Coehoorn
    Joel Coehoorn over 13 years
    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.
  • user1703401
    user1703401 over 13 years
    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.