none
Remove Line From Text File RRS feed

  • Question

  • Hello,

    My text File will contain lines as below

    A

    B

    C

    D

    I want to remove line with Text 'C' and text File should like as

    A

    B

    D

    But after removing that line my text File is Showing blank line in place of 'C'

    A

    B

    D

    How to avoid this ?

    Dim LineCount As Integer = File.ReadAllLines(dataDirectory + "\ReportFiles.ini").Length
                Dim LinesInFile As String() = File.ReadAllLines(dataDirectory + "\ReportFiles.ini")
                Dim lines As New List(Of String)(File.ReadAllLines(dataDirectory + "\ReportFiles.ini"))
                For i = 0 To LineCount - 1
                    If LinesInFile(i)= "C" Then
                        lines.RemoveAt(i)
                        File.WriteAllLines(dataDirectory + "\ReportFiles.ini", lines.ToArray())
                    End If
                Next

    Monday, November 20, 2017 5:41 AM

Answers

  • Try this.

    Public Class FileLogOperations
        Public Property FileName As String
        Public Sub New(ByVal pFileName As String)
            FileName = pFileName
        End Sub
        Public Sub New()
        End Sub
        Public Sub Strip(ByVal pText As String)
    
            Dim doubleFeed = Environment.NewLine & Environment.NewLine
    
            IO.File.WriteAllText(FileName, String.Join(
                doubleFeed, IO.File.ReadAllLines(FileName) _
                .Where(Function(line) Not line.ToLower.StartsWith(pText.ToLower) AndAlso
                Not String.IsNullOrWhiteSpace(line)).ToArray))
        End Sub
    End Class
    

    Form code

    Public Class Form1
        Private Property ops As New FileLogOperations
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            ops = New FileLogOperations(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"))
            ops.Strip("c")
        End Sub
    End Class
    

    The original file had what you had, after using the above we get

    A
    
    B
    
    D


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Tech Aspirant Tuesday, November 21, 2017 7:03 AM
    Monday, November 20, 2017 1:56 PM
    Moderator

All replies

  • But after removing that line my text File is Showing blank line in place of 'C'

    A

    B

    D

    How to avoid this ?

    I don't understand what you mean. I don't see a blank line, neither here nor when I run your code. As best as I understand, your code works for me when I run it.


    Sam Hobbs
    SimpleSamples.Info

    Monday, November 20, 2017 6:00 AM
  • After deleting when I again add one new line then It shows

    A

    B

    D

    E

    Monday, November 20, 2017 6:02 AM
  • After deleting when I again add one new line then It shows

    A

    B

    D

    E


    How do you add a new line? In a text editor or using code? I don't understand the problem. Why is that updated data incorrect? It looks valid to me.


    Sam Hobbs
    SimpleSamples.Info

    Monday, November 20, 2017 6:04 AM
  • File.AppendAllText(dataDirectory + "ReportFiles.ini", vbCrLf + "E")

    This code works fine for adding line in my file unless and until I click on delete.

    Once deleted, It adds one blank line as vbcrlf is written

    Monday, November 20, 2017 6:10 AM
  • Can you please show one demo code for adding and removing lines from text file on button click event
    Monday, November 20, 2017 6:11 AM
  • Probably the following is the problem:

    vbCrLf + "E"

    That should be:

    "E" + vbCrLf




    Sam Hobbs
    SimpleSamples.Info


    Monday, November 20, 2017 6:42 AM
  • Try this.

    Public Class FileLogOperations
        Public Property FileName As String
        Public Sub New(ByVal pFileName As String)
            FileName = pFileName
        End Sub
        Public Sub New()
        End Sub
        Public Sub Strip(ByVal pText As String)
    
            Dim doubleFeed = Environment.NewLine & Environment.NewLine
    
            IO.File.WriteAllText(FileName, String.Join(
                doubleFeed, IO.File.ReadAllLines(FileName) _
                .Where(Function(line) Not line.ToLower.StartsWith(pText.ToLower) AndAlso
                Not String.IsNullOrWhiteSpace(line)).ToArray))
        End Sub
    End Class
    

    Form code

    Public Class Form1
        Private Property ops As New FileLogOperations
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            ops = New FileLogOperations(IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"))
            ops.Strip("c")
        End Sub
    End Class
    

    The original file had what you had, after using the above we get

    A
    
    B
    
    D


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Tech Aspirant Tuesday, November 21, 2017 7:03 AM
    Monday, November 20, 2017 1:56 PM
    Moderator
  • Before posting my initial reply I tried the following:

    Dim filename As String = "G:\Temporary\ReportFiles.ini"
    Dim LineCount As Integer = File.ReadAllLines(filename).Length
    Dim LinesInFile As String() = File.ReadAllLines(filename)
    Dim lines As New List(Of String)(File.ReadAllLines(filename))
    For i = 0 To LineCount - 1
        If LinesInFile(i) = "C" Then
            lines.RemoveAt(i)
            File.WriteAllLines(filename, lines.ToArray())
        End If
    Next
    

    And I got the same results as you. So there is no problem with the code in the initial question. We have not heard from Tech Aspirant after my comment about vbCrLf so hopefully that solved the problem.



    Sam Hobbs
    SimpleSamples.Info

    Monday, November 20, 2017 6:39 PM
  • Why remove it. 

    Simply do not write it. 

            Dim x = IO.File.ReadAllLines("D:\Test\FileIn.txt")
            Using y As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("d:\test\FileOut.txt", True)
                For Each line In x
                    If line <> "C" Then
                        y.WriteLine(line)
                    End If
                Next
            End Using


    Success
    Cor

    Monday, November 20, 2017 6:58 PM
  • One reason to not automatically rewrite the file is to not update it if there is nothing to change.

    In the original code the update is within the for loop and is dependent on the presence of data to be removed. I would not do the update within the for loop but it works.



    Sam Hobbs
    SimpleSamples.Info

    Monday, November 20, 2017 9:31 PM
  • One reason to not automatically rewrite the file is to not update it if there is nothing to change.

    In the original code the update is within the for loop and is dependent on the presence of data to be removed. I would not do the update within the for loop but it works.



    Sam Hobbs
    SimpleSamples.Info

    I was curious with what kind of comment you would come. I thought it would be about the My class I used. While the code of the OP was just a sample. There is no Ini file which contains only A B C and D. But this would be if I would did it myself. (With not using that switch but that is just for the sample.) 

            Dim changed As Boolean
            Using sr As New System.IO.StreamReader("D:\Test\File.ini")
                Using sw As New System.IO.StreamWriter("d:\test\File.tmp", True)
                    Do While Not sr.EndOfStream
                        Dim line = sr.ReadLine
                        If line <> "C" Then
                            sw.WriteLine(line)
                            changed = True
                        End If
                    Loop
                End Using
            End Using
            If changed Then
                IO.File.Delete("D:\test\file.ini")
                IO.File.Move("d:\test\File.tmp", "d:\test\File.ini")
            End If
            IO.File.Delete("d:\test\File.tmp")

    With this you are sure that between the writing of the file and whatever error comes and the program goes down. The file is still available. 


    Success
    Cor





    Monday, November 20, 2017 9:58 PM
  • That provides Tech Aspirant with alternatives to consider.


    Sam Hobbs
    SimpleSamples.Info

    Monday, November 20, 2017 10:28 PM