JennaStevens
JennaStevens

Reputation: 33

Edit txt file on button click vb.net

I want to save 2 lines of numbers into a txt file and I want to add an integer of 1 on the first line and add 7 on the second line when I click a button.

So if I clicked the button once and opened the txt file it would look like this:

1 
7

and if I clicked it twice it would look like this:

2
14

I have the following code which i know is wrong as it keeps adding new lines instead of editing the existing lines.

Dim file As System.IO.StreamWriter
        file = My.Computer.FileSystem.OpenTextFileWriter("stats.txt", True)
        file.WriteLine(+1)
        file.WriteLine(+7)
        file.Close()

Thanks for your help :)

Upvotes: 3

Views: 1131

Answers (2)

Johnny Codeninja
Johnny Codeninja

Reputation: 21

'Can Try something like this

    Dim NewDocument As New List(Of String) 'List to save current and edited lines

    Using sr As New StreamReader("stats.txt")
        While Not sr.EndOfStream

            Dim Line1 As String = sr.ReadLine
            Dim Line2 As String = sr.ReadLine

            Line1 = Line1 + 1
            Line2 = Line2 + 7

            NewDocument.Add(Line1)
            NewDocument.Add(Line2)


        End While


    End Using


    If System.IO.File.Exists("stats,txt") Then
        System.IO.File.Delete(Filename)
    End If

    Using sw As New StreamWriter("stats.txt")
        For Each line As String In HL7Doc
            sw.WriteLine(line)
        Next
    End Using

Upvotes: 0

Jens
Jens

Reputation: 6385

Try first reading the lines from the file, casting the values to integer and then rewriting to the file:

Dim Lines() As String = IO.File.ReadAllLines("stats.txt")       'Returns an array of string with one element for each line. In your case 2 elements in total
Dim FirstNewNumber As Integer = CInt(Lines(0)) + 1              'Cast the first element, aka the first line, to integer and add 1
Dim SecondNewNumber As Integer = CInt(Lines(1)) + 7             'Cast the second element, aka the second line, to integer and add 7
IO.File.WriteAllText("stats.txt", FirstNewNumber.ToString & _
                     vbNewLine & _
                     SecondNewNumber.ToString)                  'Concatenate the string representations with & and insert a Newline character in between

Always remember to use the correct data types for your variables. If you use the + operator on strings it will in the best of cases concatenate the to string (aka "1" + "3" will result in "13") and in the worst case not work at all.
If you want to use arithmetic calculations use a numeric data type like integer. And be sure to enable Option Strict in your project to avoid mistakes by forcing correct data type casting. It might seems bothersome at first but trust me, it's more than worth it.

Upvotes: 3

Related Questions