0

I am currently writing a program in Visual Basic .Net.

In one specific part of the program I am trying to read from a specific line in a text file, change one of the data values in that file (data values are held separate by ",") and overwrite the same line in the same file.

Currently, the code I have written can do all of that however to make one part work I need to be able to determine the line that the data is held on to be specified, then added to a variable so that this line can be used to write to later on. Here is the code that I am talking about:

Private Sub AddC1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddC1.Click
    Dim AddC1 As String = 0
    Dim checkfile As New System.IO.StreamReader("..\..\checkfile.txt")
    Dim check As String = checkfile.ReadToEnd
    Dim objreader As New System.IO.StreamReader("..\..\usernamepassword.txt")
    Dim contents As String = objreader.ReadLine
    For i As Integer = 1 To check
        contents = objreader.ReadLine
        Dim data As New List(Of String)(contents.Split(","))
        If forname.Text = data(2) Then
            If surname.Text = data(3) Then
                AddC1 = data(8) + 1
                Exit For
            End If
        End If
    Next i
    Dim Lines() As String = System.IO.File.ReadAllLines("..\..\usernamepassword.txt")
    Lines(1) = ""
    System.IO.File.WriteAllLines("..\..\username.txt", Lines)
End Sub

Please note that this code is not finished yet. I now that this explanation doesn't make complete sense however I tried my best to explain to the best of my ability.

Thanks in advance, Alfie.

Martin Verjans
  • 4,675
  • 1
  • 21
  • 48
Alfie F
  • 1
  • 1
  • 6
  • Where is the issue? I see that you are finding the delimiter "," and getting the index. – codeMonger123 Mar 13 '17 at 19:13
  • If you are just trying to delete the line here is an example http://stackoverflow.com/questions/23755229/delete-specific-lines-in-a-text-file-using-vb-net – codeMonger123 Mar 13 '17 at 19:14

1 Answers1

1
 Dim check As String = checkfile.ReadToEnd

should be

Dim check = File.ReadAllLines("..\..\checkfile.txt").Length

which will give you the number of lines in the file. Otherwise,

For i As Integer = 1 To check

will give you an error. Can't go from an integer to a string. You can declare another variable and set it equal to i - 1 (since your for loop is starting from 1 instead of 0) inside your inner if loop which will give you the value of the index for later usage.

obl
  • 1,799
  • 12
  • 38