none
Overwritting line in the text file RRS feed

  • Question

  • In this program user is asked to enter username and password. Each user has usernamae|pass|balance is stored in text file.  Once those details are correct those variables are being passed to second form.

    When user will click on button, balance will get decrement by specific value. I would like to overwrite sameuser|samepass|newbalance without duplicate in the text file, which is happening right now.

    Can somebody give me suggestion how to fix this problem? Thanks

    Option Strict On

    Option Explicit On

    Imports System.IO

     

    Public Class Form1

     

        Public user As String

        Public pass As String

        Public TopAmount As String

     

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

     

            Using login As StreamReader = New StreamReader("..\..\TextFile\users.txt", True)

     

                user = txtUsername.Text

                pass = txtPassword.Text

     

                While Not login.EndOfStream

     

                    Dim break As String() = login.ReadLine.Split(Convert.ToChar("|"))

                    user = break(0)

                    pass = break(1)

                    TopAmount = break(2)

     

                    If txtUsername.Text = break(0) AndAlso txtPassword.Text = break(1) Then

                        frmguest.Show()

     

                    End If

                End While

            End Using

     

        End Sub

    End Class

    Option Explicit On

    Option Strict On

    Imports System.IO

     

    Public Class frmguest

     

        Dim loggedUser As String

        Dim loggedPass As String

        Dim userAmount As Double

     

     

     

        Private Sub frmguest_Load(sender As Object, e As EventArgs) Handles MyBase.Load

            loggedUser = Form1.user

            loggedPass = Form1.pass

            userAmount = CDbl(Form1.TopAmount)

     

        End Sub

     

        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

     

            Dim price As Double = 1.1

            If CheckBox1.Checked = True Then

                userAmount = userAmount - price

                Label1.Text = userAmount.ToString("n1")

     

            End If

     

     

        End Sub

     

        Private Sub frmguest_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed

            Using writer As StreamWriter = New StreamWriter("..\..\TextFile\users.txt", True)

     

                writer.WriteLine(loggedUser & "|" & loggedPass & "|" & userAmount)

                writer.Close()

            End Using

        End Sub

    End Class

    Saturday, January 20, 2018 8:01 PM

Answers

  • Hey

    Well what I meant is username and password are being write again with new balance. My text file is small maybe 50 lines.

     Example:

    john|12345|56.80

    samantha|12edg|15.60

    john|12345|55.00

    So instead creating the same user twice I would prefer find the user and replace with new details. Thanks

    Hi

    Seems a lot of unnecessary data passing involved, however, here is some code that tries to keep some semblance to your original but with changes as needed.

    Try it out and see if it is close to your requirements.

    Form1

    Option Strict On
    Option Explicit On
    Imports System.IO
    Public Class Form1
      Public user As String
      Public pass As String
      Public TopAmount As String
    
      Dim path As String = "C:\Users\lesha\Desktop\Plans\New folder\TestNamePass.txt"
    
      Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    
    	Dim lines() As String = File.ReadAllLines(path)
    
    	For Each line As String In lines
    	  Dim s() As String = line.Split("|"c)
    
    	  If s(0) = txtUsername.Text AndAlso s(1) = txtPassword.Text Then
    		Dim Form2 As New frmguest
    		Form2.loggedUser = s(0)
    		Form2.loggedPass = s(1)
    		Form2.userAmount = CDbl(s(2))
    		Form2.path = path
    		Form2.lines = lines
    		Form2.Show()
    		Exit For
    	  End If
    	Next
      End Sub
    End Class

    Form2

    Option Explicit On
    Option Strict On
    Imports System.IO
    Public Class frmguest
      Property loggedUser As String
      Property loggedPass As String
      Property userAmount As Double
      Property path As String
      Property lines As String()
      Private Sub frmguest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      End Sub
      Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    	Dim price As Double = 1.1
    	If CheckBox1.Checked = True Then
    	  userAmount = userAmount - price
    	  Label1.Text = userAmount.ToString("n1")
    	  For line As Integer = 0 To lines.Count - 1
    		Dim s() As String = lines(line).Split("|"c)
    		If s(0) = loggedUser AndAlso s(1) = loggedPass Then
    		  lines(line) = loggedUser & "|" & loggedPass & "|" & Label1.Text
    		End If
    	  Next
    	End If
      End Sub
      Private Sub frmguest_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    	File.WriteAllLines(path, lines)
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    Saturday, January 20, 2018 9:08 PM

All replies

  • Hi

    If I understand your question correctly, and looking through your code, I wonder if you might do better to read in all lines, update appropriate line (second Form) and then write all lines.

    If your text file doesn't have a tremendous number of lines.

    You also need to explain what is actually happening with your current code rather than just saying 'which is happening right now' - suggesting that all is working as expected.


    Regards Les, Livingston, Scotland

    Saturday, January 20, 2018 8:12 PM
  • I would like to overwrite sameuser|samepass|newbalance without duplicate in the text file, which is happening right now.

    The simplest procedure is to read the whole file into memory, make the changes, and write the whole file out, overwriting whatever was there before.  You would use an array of String to get the whole file into memory.  

    See:
    https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx
    https://msdn.microsoft.com/en-us/library/92e05ft3(v=vs.110).aspx

    When you have the whole file in an array you would use code similar to the existing Button1_Click event code to find the index in the array of the line that matches the username.   Then you make the change to the amount, create a new line of text for the array, insert that line into that index position in the array, and write the whole array.

    An alternative is to read the file line-by-line, examining each line for a match to the username.  If it's the line you want, make the required changes.  Otherwise, leave it unchanged.  Then write the line to the output file.  Continue untilt he end of file.   Then delete the original input file and rename the output file with the original filename.

    Saturday, January 20, 2018 8:20 PM
  • In this program user is asked to enter username and password. Each user has usernamae|pass|balance is stored in text file.

    That sounds like you'd be better off with a class and use XML to transfer information to other users.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Saturday, January 20, 2018 8:24 PM
  • Hey

    Well what I meant is username and password are being write again with new balance. My text file is small maybe 50 lines.

     Example:

    john|12345|56.80

    samantha|12edg|15.60

    john|12345|55.00

    So instead creating the same user twice I would prefer find the user and replace with new details. Thanks

    Saturday, January 20, 2018 8:24 PM
  • So instead creating the same user twice I would prefer find the user and replace with new details. Thanks

    The suggestions provided will do that - read the whole file into memory, change what needs to be changed, and write the whole file out again.   Or, read each line, change it if needed, and write each line to a new file.
    Saturday, January 20, 2018 8:46 PM
  • Hey

    Well what I meant is username and password are being write again with new balance. My text file is small maybe 50 lines.

     Example:

    john|12345|56.80

    samantha|12edg|15.60

    john|12345|55.00

    So instead creating the same user twice I would prefer find the user and replace with new details. Thanks

    Hi

    Seems a lot of unnecessary data passing involved, however, here is some code that tries to keep some semblance to your original but with changes as needed.

    Try it out and see if it is close to your requirements.

    Form1

    Option Strict On
    Option Explicit On
    Imports System.IO
    Public Class Form1
      Public user As String
      Public pass As String
      Public TopAmount As String
    
      Dim path As String = "C:\Users\lesha\Desktop\Plans\New folder\TestNamePass.txt"
    
      Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    
    	Dim lines() As String = File.ReadAllLines(path)
    
    	For Each line As String In lines
    	  Dim s() As String = line.Split("|"c)
    
    	  If s(0) = txtUsername.Text AndAlso s(1) = txtPassword.Text Then
    		Dim Form2 As New frmguest
    		Form2.loggedUser = s(0)
    		Form2.loggedPass = s(1)
    		Form2.userAmount = CDbl(s(2))
    		Form2.path = path
    		Form2.lines = lines
    		Form2.Show()
    		Exit For
    	  End If
    	Next
      End Sub
    End Class

    Form2

    Option Explicit On
    Option Strict On
    Imports System.IO
    Public Class frmguest
      Property loggedUser As String
      Property loggedPass As String
      Property userAmount As Double
      Property path As String
      Property lines As String()
      Private Sub frmguest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      End Sub
      Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    	Dim price As Double = 1.1
    	If CheckBox1.Checked = True Then
    	  userAmount = userAmount - price
    	  Label1.Text = userAmount.ToString("n1")
    	  For line As Integer = 0 To lines.Count - 1
    		Dim s() As String = lines(line).Split("|"c)
    		If s(0) = loggedUser AndAlso s(1) = loggedPass Then
    		  lines(line) = loggedUser & "|" & loggedPass & "|" & Label1.Text
    		End If
    	  Next
    	End If
      End Sub
      Private Sub frmguest_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    	File.WriteAllLines(path, lines)
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    Saturday, January 20, 2018 9:08 PM
  •  Here is another example which you can try too...

    Form1 Code...

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim FileLines() As String = IO.File.ReadAllLines("C:\testfolder\userdata.txt")
            For i As Integer = 0 To FileLines.Length - 1
                Dim parts() As String = FileLines(i).Split("|"c)
                If parts(0) = txtUsername.Text AndAlso parts(1) = txtPassword.Text Then
                    Using f2 As New Form2
                        f2.StartPosition = FormStartPosition.CenterParent
                        f2.UserAmount = CDbl(parts(2))
                        If f2.ShowDialog(Me) = DialogResult.OK Then
                            parts(2) = f2.UserAmount.ToString
                            FileLines(i) = String.Join("|", parts)
                            IO.File.WriteAllLines("C:\testfolder\userdata.txt", FileLines)
                        End If
                    End Using
                    Exit For
                End If
            Next
        End Sub
    End Class
    
     

     Form2 Code...

    Public Class Form2
        Public Property UserAmount As Double
    
        Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Label1.Text = UserAmount.ToString("C2")
        End Sub
    
        Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
            If CheckBox1.Checked Then
                UserAmount -= 1.55
            Else
                UserAmount += 1.55
            End If
            Label1.Text = UserAmount.ToString("C2")
        End Sub
    
        Private Sub Button_Ok_Click(sender As Object, e As EventArgs) Handles Button_Ok.Click
            Me.DialogResult = DialogResult.OK
        End Sub
    End Class

     

     This is the data in the text file...

    John|12345|56.80
    Samantha|12edg|15.60
    IronRazerz|abc|22.50
    Jack|y2ux|39.75
     

     Here i show Form2 and check the checkbox to buy something,  and then press the Ok button to verify that i wanted to buy it.  If i just close Form2,  nothing will be subtracted from the user amount.

     

     Now the file looks like below.  My amount is $1.55 less...

    John|12345|56.80
    Samantha|12edg|15.60
    IronRazerz|abc|20.95
    Jack|y2ux|39.75


    If you say it can`t be done then i`ll try it

    Saturday, January 20, 2018 9:43 PM
  • Hey

    Well what I meant is username and password are being write again with new balance. My text file is small maybe 50 lines.

     Example:

    john|12345|56.80

    samantha|12edg|15.60

    john|12345|55.00

    So instead creating the same user twice I would prefer find the user and replace with new details. Thanks

    Hi

    Seems a lot of unnecessary data passing involved, however, here is some code that tries to keep some semblance to your original but with changes as needed.

    Try it out and see if it is close to your requirements.

    Form1

    Option Strict On
    Option Explicit On
    Imports System.IO
    Public Class Form1
      Public user As String
      Public pass As String
      Public TopAmount As String
    
      Dim path As String = "C:\Users\lesha\Desktop\Plans\New folder\TestNamePass.txt"
    
      Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    
    	Dim lines() As String = File.ReadAllLines(path)
    
    	For Each line As String In lines
    	  Dim s() As String = line.Split("|"c)
    
    	  If s(0) = txtUsername.Text AndAlso s(1) = txtPassword.Text Then
    		Dim Form2 As New frmguest
    		Form2.loggedUser = s(0)
    		Form2.loggedPass = s(1)
    		Form2.userAmount = CDbl(s(2))
    		Form2.path = path
    		Form2.lines = lines
    		Form2.Show()
    		Exit For
    	  End If
    	Next
      End Sub
    End Class

    Form2

    Option Explicit On
    Option Strict On
    Imports System.IO
    Public Class frmguest
      Property loggedUser As String
      Property loggedPass As String
      Property userAmount As Double
      Property path As String
      Property lines As String()
      Private Sub frmguest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
      End Sub
      Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
    	Dim price As Double = 1.1
    	If CheckBox1.Checked = True Then
    	  userAmount = userAmount - price
    	  Label1.Text = userAmount.ToString("n1")
    	  For line As Integer = 0 To lines.Count - 1
    		Dim s() As String = lines(line).Split("|"c)
    		If s(0) = loggedUser AndAlso s(1) = loggedPass Then
    		  lines(line) = loggedUser & "|" & loggedPass & "|" & Label1.Text
    		End If
    	  Next
    	End If
      End Sub
      Private Sub frmguest_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    	File.WriteAllLines(path, lines)
      End Sub
    End Class


    Regards Les, Livingston, Scotland

    In the second form in For line As Integer = 0 To Lines.Count -1

    Im getting error SystemArgumentNullException- details : Value cannot be null. When I try to use debugger it says lines values Nothing

    Sunday, January 21, 2018 12:02 AM
  • Hey

    Well what I meant is username and password are being write again with new balance. My text file is small maybe 50 lines

    It's data.

    Treat it like data and it will behave like data, no matter the format you choose to convey it.


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, January 21, 2018 12:06 AM
  • In the second form in For line As Integer = 0 To Lines.Count -1

    Im getting error SystemArgumentNullException- details : Value cannot be null. When I try to use debugger it says lines values Nothing

    Hi

    It works here OK.

    Put a break point at the line 'Form2.lines = lines' of Form1 and check if lines does have the correct data, then single step into the second form and check if the Property Lines has the data.

    In my trials here, everything does work OK, and the data is correctly carried over into the second Form.


    Regards Les, Livingston, Scotland

    Sunday, January 21, 2018 12:17 AM