Delete entire line if it contains specific word - vb.net

I also want to display the line containing the word. I want to open an external .txt file and delete any line if it contains a specific string. I have a search and replace at the moment for one word but want the entire line to be removed from the file. Thanks
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamReaderL1 As System.IO.StreamReader
Dim myStream As System.IO.StreamWriter
Dim myStr As String
myStreamReaderL1 = System.IO.File.OpenText("C:\Users\f1r1a\Desktop\memes.txt")
myStr = myStreamReaderL1.ReadToEnd()
myStreamReaderL1.Close()
myStr = myStr.Substring("fraser", 6)
'Save myStr
myStream = System.IO.File.CreateText("C:\Users\f1r1a\Desktop\memes.txt")
myStream.WriteLine(myStr)
myStream.Close()
End Sub

Well you can do all of that code in two lines
Dim result = File.ReadLines("C:\Users\f1r1a\Desktop\memes.txt").
Where(Function(x) Not x.Contains("fraser"))
File.WriteAllLines("C:\Users\f1r1a\Desktop\memes.txt", result.ToArray)
The IEnumerable extension Where receives, line by line, the sequence produced by File.ReadLines. Each line is processed by Where applying the Contains method and if the line doesn't contains the word searched then it is passed as output to the result variable. In turn the result variable is passed as an array to the WriteAllLines method.

You can get both at once:
Dim file = "C:\Users\f1r1a\Desktop\memes.txt"
Dim lookup = File.ReadLines(file).ToLookup(Function(l) l.Contains("fraser"))
textBoxRemoved.Text = String.Join("|", lookup(True))
File.WriteAllLines(file, lookup(False))

Related

Copy serial numbers from string or txt file to Listbox

I have a string or a text file which contains some software serial number among other information.
I’m trying to pull out the software serial numbers which all start with EAN- and send them to a listbox.
Example of the string or text file:
2
EAN-3E4R5-5TGGG-6667Y
Software name Technology
PO #PORD-11111
INV-219149
3
EAN-SXDR5-5DDD-6DDDY
Software name Technology
PO #PORD-11111
INV-219149
I'm after just the serial numbers beging with EAN-.
So the listbox would be
EAN-3E4R5-5TGGG-6667Y
EAN-SXDR5-5DDD-6DDDY
This code would work:
Dim strBuf As String
strBuf = "EAN-3E4R5-5TGGG-6667Y Software nam.............."
Dim Tokens1() As String
Tokens1 = Split(strBuf, "EAN-")
For I = 1 To UBound(Tokens1)
Dim OneListItem As String = "EAN-" & Split(Tokens1(I), " ")(0)
ListBox1.Items.Add(OneListItem)
Next
I read the file with .ReadAllLines which returns an array of the lines in the file. I looped through the lines and if a line started with EAN- it was added to the list. Then the list is bound to the ListBox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lstSerialNums As New List(Of String)
Dim lines = File.ReadAllLines("C:\Users\maryo\Desktop\Code\Serial Numbers.txt")
For Each line In lines
If line.StartsWith("EAN-") Then
lstSerialNums.Add(line)
End If
Next
ListBox1.DataSource = lstSerialNums
End Sub
With a small amount of LINQ, you can make quite readable code:
Dim srcFile = "C:\temp\SO67550806.txt"
Dim eans = File.ReadLines(srcFile).Where(Function(s) s.StartsWith("EAN-")).ToList()
yourListBoxName.DataSource = eans

How can I ignore a new line character when reading CSV file in VB.NET?

I wrote a utility in VB.NET that reads an input CSV file, does some processing (specifically it ignores the first 5 lines of the input file and replaces them with a header row saved in another file) and writes the information from the input file into a new output CSV file.
Where my program fails is when the input data includes new line characters within one column value within the CSV.
I would like to ignore the new line character within a CSV data row when I load it into my string array.
Here is my code (its embedded in a form)
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim incsvPath = strFileName
Dim outcsvPath = fi.DirectoryName & "\" & outfilename
Dim headerPath = fi.DirectoryName & "\ACTIVITY_HISTORY_HEADER.csv"
Dim fileP As String = incsvPath
Dim fileheader As String = headerPath
Dim CSVheaderIn As New ArrayList
Dim CSVlinesIn As New ArrayList
Dim CSVout As New List(Of String)
CSVheaderIn.AddRange(IO.File.ReadAllLines(fileheader))
CSVlinesIn.AddRange(IO.File.ReadAllLines(fileP))
messageTB.AppendText(vbCrLf & vbCrLf)
For Each line As String In CSVheaderIn
Dim nameANDnumber As String() = line.Split(",")
messageTB.AppendText("csv file header row = " & line & vbCrLf & vbCrLf & "csv file contents follow ..." & vbCrLf)
CSVout.Add(line)
Next
Dim mySubAL As ArrayList = CSVlinesIn.GetRange(5, CSVlinesIn.Count - 5)
For Each line As String In mySubAL 'CSVlinesIn
messageTB.AppendText(line & vbCrLf)
CSVout.Add(line)
Next
IO.File.WriteAllLines(outcsvPath, CSVout.ToArray)
End Sub
This is fairly hard work actually; it'll be easier to use a library that knows how to read and write CSV with newlines in the data than roll your own - not saying you couldn't, but it's a wheel that has already been invented so why do it again?
I used Steve Hansen's Csv - right click your project in solution explorer, choose Manage Nuget Packages, click Browse, Search csv, install the right one
Imports System.Text
Imports Csv
Imports System.IO
Module Module1
Sub Main(args As String())
'open the headers file
Using hIn = File.OpenText("C:\temp\h.csv")
'setup instruction to the csv reader with headersabsent flag so we can get the first line as data
Dim hOptions = New CsvOptions With {.HeaderMode = HeaderMode.HeaderAbsent}
'take the first line into an array - these are our headers
Dim headers = CsvReader.Read(hIn, hOptions)(0).Values
'open the data file,
Using fIn = File.OpenText("C:\temp\a.csv")
'setup instruction for the reader to skip 5 rows, treat first row as data, and allow newlines in quoted fields
Dim fOptions = New CsvOptions With {.RowsToSkip = 5, .HeaderMode = HeaderMode.HeaderAbsent, .AllowNewLineInEnclosedFieldValues = True}
Using fOut = File.CreateText("C:\temp\a_out.csv")
'convert the ICsvLine rows in the reader to rows of String() that the writer will accept, and write them under the headers
CsvWriter.Write(fOut, headers, CsvReader.Read(fIn, fOptions).Select(Function(line) line.Values))
End Using
End Using
End Using
End Sub
End Module
You don't have to use this lib to read the headers; you could just file.ReadText().ReadLine().Split(","c) it
If you want to perform per-line processing on the elements, do this:
CsvWriter.Write(fOut, headers, CsvReader.Read(fIn, fOptions).Select(Function(line) ProcessLine(line.Values)))
...
Function ProcessLine(input As String()) As String()
'Note: If(input(8), "") returns input(8) unless it is nothing in which case "" is returned instead
If If(input(8), "").Length > 10 Then input(8) = input(8).Remove(10) 'Trim if over 10
If If(input(14), "").Length > 10 Then input(14) = input(14).Remove(10)
Return input 'Always return
End Function

VB.Net Search for text and replace with file content

This is a follow on question to a post I made. Append one file into another file
I need to search the master document for entities "&CH1.sgm" to "&CH33.sgm",
mark where they are in the master document and replace the entity call with the matching file "Chapter1.sgm" found in "fnFiles". I can change the file names and entities to anything if that will help.
My code copies the text of a file and appends it to the bottom of the master_document.sgm. But now I need it to be more intelligent. Search the Master document for entity markers, then replace that entity marker with that file contents match. The file number and entity number match up. e.g.(&CH1; and Bld1_Ch1.sgm)
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
Dim searchDir As String = txtSGMFile.Text 'Input field from form
Dim masterFile = "Bld1_Master_Document.sgm"
Dim existingFileMaster = Path.Combine(searchDir, masterFile)
'Read all lines of the Master Document
Dim strMasterDoc = File.ReadAllText(existingFileMaster) '// add each line as String Array.
'?search strMasterDoc for entities &Ch1.sgm
'?replace entity name "&Ch1.sgm" with content of file "Bld1_Ch1.sgm" this content if found below
'? do I use a book mark? Replace function?
'Get all the sgm files in the directory specified
Dim fndFiles = Directory.GetFiles(searchDir, "*.sgm")
'Set up the regular expression you will make as the condition for the file
Dim rx = New Regex(".*_Ch\d\.sgm")
Dim ch1 = New Regex(".*_Ch[1]\.sgm")
'Use path.combine for concatenatin directory together
'Loop through each file found by the REGEX
For Each fileNo In fndFiles
If rx.IsMatch(fileNo) Then
If ch1.IsMatch(fileNo) Then
Dim result = Path.GetFileName(fileNo)
'Use path.combine for concatenatin directory together
Dim fileToCopy = Path.Combine(searchDir, result)
'This is the file we want to copy into MasterBuild but at specific location.
'match &ch1.sgm inside strMasterDoc
Dim fileContent = File.ReadAllText(fileToCopy)
'Search master file for entity match then append all content of fileContent
File.AppendAllText(existingFileMaster, fileContent)
MessageBox.Show("File Copied")
End If
End If
Next
Close()
End Sub
If I understand correctly (big if), you want to replace the the text of the abbreviated chapter name in the master file with the contents of the file it refers to at the spot where the abbreviation is found.
I made a class to handle the details.
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
'Add a FolderBrowseDialog to your form designer
FolderBrowserDialog1.ShowDialog()
Dim searchDir As String = FolderBrowserDialog1.SelectedPath
Dim existingFileMaster = Path.Combine(searchDir, "Bld1_Master_Document.sgm")
Dim lstFileChanges = CreateList(searchDir)
'The following method does NOT return an array of lines
Dim strMasterDoc = File.ReadAllText(existingFileMaster)
For Each fc In lstFileChanges
strMasterDoc = strMasterDoc.Replace(fc.OldString, fc.NewString)
Next
File.WriteAllText(existingFileMaster, strMasterDoc)
End Sub
Private Function CreateList(selectedPath As String) As List(Of FileChanges)
Dim lstFC As New List(Of FileChanges)
For i = 1 To lstFC.Count
Dim fc As New FileChanges
fc.OldString = $"&CH{i}.sgm"
fc.FileName = $"Chapter{i}.sgm"
fc.NewString = File.ReadAllText(Path.Combine(selectedPath, fc.FileName))
lstFC.Add(fc)
Next
Return lstFC
End Function
Public Class FileChanges
Public Property OldString As String '&CH1.sgm
Public Property FileName As String 'Chapter1.sgm
Public Property NewString As String 'Contents of Chapter1.sgm, the string to insert
End Class
Testing .Replace
Dim s As String = "The quick brown fox jumped over the lazy dogs."
s = s.Replace("fox", "foxes")
MessageBox.Show(s)

Reading from text file to ListBox

I am having a bit of trouble reading data from a text file. This almost works, however data in separate lines in the text file is combined to one long line in the ListBox. How else to do it?
Private Sub frmOpretrskAar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
LBmuligeFirmaer.Items.Add(objReader.ReadToEnd)
objReader.Close()
End Sub
Use the ListBox.Items.AddRange method to add an array, in this case it would be an array that represents the lines of the text file. You can get the lines by using IO.File.ReadAllLines method. Here is a quick example:
LBmuligeFirmaer.Items.AddRange(IO.File.ReadAllLines("c:\users\claus\onedrive\SLERP\fmr.txt"))
Its very simple -
List<string> _list = File.ReadAllLines(fileName).ToList();
See the below image -
You can use array.
Try this code:
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
Dim AllLines() As String = System.IO.File.ReadAllLines(FILE_NAME)
For i As Integer = 0 To AllLines.Count - 1
LBmuligeFirmaer.Items.Add(AllLines(i))
Next
I can't test this in my IDE currently so tell me if something doesn't work right but I have used something similar:
Imports System.IO
Imports System.Windows.Forms
'assigning a string value to the file's location
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
'clearing the listbox
LBmuligeFirmaer.items.clear
'declaring a filereader
Dim fileReader As System.IO.StreamReader
fileReader =
'obtaining file location from string to the stringreader
My.Computer.FileSystem.OpenTextFileReader(FILE_NAME)
Dim stringReader As String
'reading first line
stringReader = fileReader.ReadLine()
'adding line to the listbox
LBmuligeFirmaer.items.add(stringreader)
'reading second line
stringReader = fileReader.ReadLine()
'adding line to listbox
LBmuligeFirmaer.items.add(stringreader)
'and so on...

VB.NET - It keep replacing itself

I have in a text file lines of this format:
word1|word2|word3
anotherword1|anotherword2
I'm trying to split each word one by one per every line of that file and once program detect if the richtextbox has one of these words will replace that word with the unsplitted line. Example: From word1 to word1|word2|word3
Here is what I have so far:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
For Each line As String In File.ReadLines("C:\text.txt")
Dim input As String = line
Dim result As String() = line.Split(New String() {"|"}, StringSplitOptions.None)
For Each s As String In result
Try
Dim linex As String = line
RichTextBox1.Text = RichTextBox1.Text.Replace(s, " " & linex)
Catch exxx As Exception
End Try
Next
Next
End Sub
It works great, but after the replacement, the replaced text still have the detected word and it keep replacing itself with word1|word2|word3 forever. And I want do do the process just once.
Like this: Click to see
Due to the format the words are stored in, it will be much easier to achieve what you want using Regular Expressions:
Dim lines = File.ReadLines("C:\text.txt")
For Each line As String In lines
Dim pat = String.Format("\b({0})\b", line)
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, pat, line)
Next
This should do pretty much what you want.
Check it here.