Hello all, zoidmaster here. I have a question regarding Visual Basic and deleting lines of text from files. I'm trying to make a piece of software to manage customers who walk into a store. I got most of it written already but the problem I'm running into is deleting some text from my text file. The reason I'm starting a new thread for this is because no matter where I look I can't find a thread on any site (not just daniweb) that explains how to do this in visual basic and not vb.net or vbscript.

Here's the code from the private sub I'm working in:

Private Sub btnDone_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDone.Click
        Dim data As StreamWriter 'Sets the variable to house all data being written to the file
        Dim fileDateTime As String = DateTime.Now.ToString("yyyyMMdd")
        data = My.Computer.FileSystem.OpenTextFileWriter("C:\Customer Assistance Kiosk\CAK_FINAL\" + fileDateTime + ".txt", True) 'Opens the file to write to and ammends all incoming lines of text

        If System.IO.File.Exists("C:\Customer Assistance Kiosk\CAK_FINAL\" + fileDateTime + ".txt") = True Then
            data.WriteLine("Customer Name: " + lblName.Text) 'Writes line of text from the name box
            data.WriteLine("Customer Reason: " + lblReason.Text) 'Writes line of text from the combo box
            data.WriteLine("Employee Number: " + txtEmpNum.Text) 'Writes line of text from the text box
            data.WriteLine("-------------------------------------------") 'Inserts line separator between pieces of data in the file
            data.Close() 'Closes the file after writing to it
            lblName.Text = "" 'Clears the text box for the next customer's name
            lblReason.Text = "" 'Clears the combo box for the next customer's reason
            txtEmpNum.Text = "" 'Clears the text box for the next employee's number
            Me.Close()
        Else
            System.IO.File.Create("C:\Customer Assistance Kiosk\CAK_FINAL\" + fileDateTime + ".txt") 'Creates the file to house the information

            data.WriteLine("Customer Name: " + lblName.Text) 'Writes line of text from the name box
            data.WriteLine("Customer Reason: " + lblReason.Text) 'Writes line of text from the combo box
            data.WriteLine("Employee Number: " + txtEmpNum.Text) 'Writes line of text from the text box
            data.WriteLine("-------------------------------------------") 'Inserts line separator between pieces of data in the file
            data.Close() 'Closes the file after writing to it
            lblName.Text = "" 'Clears the text box for the next customer's name
            lblReason.Text = "" 'Clears the combo box for the next customer's reason
            txtEmpNum.Text = "" 'Clears the text box for the next employee's number
            Dim lines As New List(Of String)(File.ReadAllLines("C:\Customer Assistance Kiosk\CAK_DATA\DATA.cak"))

            'Remove the line to delete, e.g.
            lines.RemoveAt(1)
            lines.RemoveAt(2)

            File.WriteAllLines("C:\Customer Assistance Kiosk\CAK_DATA\DATA.cak", lines.ToArray())
            Me.Close()
        End If

    End Sub

Basically what I'm trying to do here is take a file that is made in another portion of the program and delete the first two lines out of it. From what I can tell everything else works, including the portion that copies the data from one file to the other. I just don't know how to get rid of those two lines in the first file.

Any help would be much appreciated. Thank you. -Zoidmaster

Recommended Answers

All 11 Replies

Can you load the entire file into memory?

If so, load the whole thing
- skip or eliminate the data you don't want
- rewrite the file.

Can you give me an example of rewriting the file, that is what I don't know how to do. Trying to make sure I understand this for future reference.

Sure (technique 1):

Imports System.IO
Imports System.Linq

Module Module1
   Public Function DeleteTopTwoLines(ByVal strFileName As String, ByRef strError As String) As Boolean
      Dim blnRetVal As Boolean = True
      Try
         Dim strData() As String = File.ReadAllLines(strFileName)
         File.WriteAllLines(strFileName, strData.ToList().Skip(2).ToArray())
      Catch ex As Exception
         blnRetVal = False
         strError = ex.Message
      End Try

      Return blnRetVal
   End Function

   Sub Main()
      Dim strError As String = ""
      If (Not (DeleteTopTwoLines("c:\science\Text1.txt", strError))) Then
         System.Diagnostics.Debug.WriteLine("Could not process file: " + strError)
         Return
      End If
   End Sub
End Module

The code does not work in Visual Basic. If it is supposed to can you explain how? I copied the function in and it says "Statement is not valid within a namespace."

Which statement?

Did you add the Imports?

I did add the Imports System.Linq, I already had the Imports System.IO. I copied this code and placed it outside the public sub already in the program like this:

Imports System.IO
Imports System.Linq

Public Function DeleteTopTwoLines(ByVal strFileName As String, ByRef strError As String) As Boolean
    Dim blnRetVal As Boolean = True
    Try
        Dim strData() As String = File.ReadAllLines(strFileName)
        File.WriteAllLines(strFileName, strData.ToList().Skip(2).ToArray())
    Catch ex As Exception
        blnRetVal = False
        strError = ex.Message
    End Try

    Return blnRetVal
End Function

Public Class frmEmp

    Private Sub frmEmp_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim data1 As StreamReader

        data1 = New StreamReader("C:\Customer Assistance Kiosk\CAK_DATA\DATA.cak")
        lblName.Text = data1.ReadLine()
        lblReason.Text = data1.ReadLine()

    End Sub

Did I place it in the wrong location in my code?

Edit: Just to note Visual Studio gave me an error with: Public Function DeleteTopTwoLines(ByVal strFileName As String, ByRef strError As String) As Boolean

Yes, the function should be INSIDE the class.

Ok it likes it now. Here's another question for you, can I stick this code inside the sub I posted originally or does it need to be in a sub on its own?

Dim strError As String = ""
      If (Not (DeleteTopTwoLines("c:\science\Text1.txt", strError))) Then
         System.Diagnostics.Debug.WriteLine("Could not process file: " + strError)
         Return
      End If

Edit: I also don't understand how I'm going to integrate that with the rest of the program. How does the function work with my sub that manipulates the files?

You can use it wherever you want.

I think routines like that need to be kept separate so they can wiork without being bound to the display or a particular piece of code.
All you need to pass to it are the parameters.
I might even add in a new parameter that is the number of lines to delete from the top.

It can also be modified to eliminate lines that contain particular data pieces.

There are a LOT of options.

... no matter where I look I can't find a thread on any site (not just daniweb) that explains how to do this in visual basic and not vb.net or vbscript....

Basically what I'm trying to do here is take a file that is made in another portion of the program and delete the first two lines out of it. From what I can tell everything else works, including the portion that copies the data from one file to the other. I just don't know how to get rid of those two lines in the first file.

Any help would be much appreciated. Thank you. -Zoidmaster

First of all, the technique is the same no matter what language you use.

Granted, I didn't read all these posts because the solution is soooo simple, and you claim you have "the portion that copies the data from one file to the other" working, so the solution is

Ready...?

Read the first two lines of the file.
Now copy the rest of the file with the portion that works.

By reading the first to lines, they are no longer available to be read so will be gone from the copied file.


IOW, read the file; write only the lines you want copied, don't write the rest.

None of this stuff works. I am unable to get any help from this because the code given does not work with Visual Basic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.