Baseult Private
Baseult Private

Reputation: 85

VB.Net Read Text File Line by Line and remove non alpha text

So I want to read a .txt file Line by Line and check if the current line has alpha characters in it.

If not I want to remove that Line and then continue with the next Line.

I tried to do it like this and it detects the non alpha strings. All I need is the function to remove the current line or string out of the txt file. Im handling Bigsized Files (up to 2gb) So reading the whole text and searching for the current string to remove it is probably a kinda bad and timewasting idea:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim FILE_NAME As String = "E:\combo.txt"
        Dim TextLine As String

        If System.IO.File.Exists(FILE_NAME) = True Then

            Dim objReader As New System.IO.StreamReader(FILE_NAME)

            Do While objReader.Peek() <> -1
                TextLine = objReader.ReadLine() & vbNewLine
                If CheckForAlphaCharacters(TextLine) = True Then
                    'Removeline
                End If
            Loop

            MessageBox.Show("File Does Not Exist")

        End If
    End Sub

    Function CheckForAlphaCharacters(ByVal StringToCheck As String)
        For i = 0 To StringToCheck.Length - 1
            If Char.IsLetter(StringToCheck.Chars(i)) Then
                Return False
            End If
        Next

        Return True 'Return True if all chars are not characters
    End Function

Upvotes: 0

Views: 501

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

You can do it all in one line, believe it or not:

Dim nonAlphaLines = File.ReadLines(FILE_NAME) _ 
  .Where(Function(x) Not x.Any(Function(c) Char.IsLetter(c))) _
  .ToArray()

For example, here is a file:

123
abc
456

After you finish running the code above you will have an array like:

You might not even need the ToArray but you didn't really specify what you wanted to do with your nonalpha lines

nonAlphaLines = { "123", "456" }

Do with this array what you want.

If you want to remove alpha lines from a file and have the same file at the end i.e. you want to clean the file, you could do this if the file is small:

File.WriteAllLines(FILE_NAME, _
  File.ReadAllLines(FILE_NAME) _
    .Where(Function(x) Not x.Any(Function(c) Char.IsLetter(c))) _
  ) _
)

If the file is large it would be better not to load it into memory; use ReadLines rather than ReadAllLines and write to a NEW_FILE_NAME:

File.WriteAllLines(NEW_FILE_NAME, _
  File.ReadAllLines(FILE_NAME) _
    .Where(Function(x) Not x.Any(Function(c) Char.IsLetter(c))) _
  ) _
)

Upvotes: 0

Related Questions