Loop through the lines of a text file in VB.NET - vb.net

I have a text file with some lines of text in it.
I want to loop through each line until an item that I want is found*, then display it on the screen, in the form of a label.
*I am searching for the item through a textbox.
That is, in sudo:
For i = 0 To number of lines in text file
If txtsearch.text = row(i).text Then
lbl1.text = row(i).text
Next i

You can use the File.ReadLines Method in order to iterate throughout your file, one line at a time. Here is a simple example:
Dim Term As String = "Your term"
For Each Line As String In File.ReadLines("Your file path")
If Line.Contains(Term) = True Then
' Do something...Print the line
Exit For
End If
Next

Here's a function that will spit back your string from the row that contains your search term...
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
To use the function you can do this...
Dim strText As String = SearchFile(FileName, SearchTerm)
If strText <> String.Empty Then
Label1.Text = strText
End If

LOOPING AND GETTING ALL XML FILES FROM DIRECTORY IF WE WANT TEXTFILES PUT "*.txt" IN THE PLACE OF "*xml"
Dim Directory As New IO.DirectoryInfo(Path)
Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.xml")
allFiles = allFiles.OrderByDescending(Function(x) x.FullName).ToArray()
Dim singleFile As IO.FileInfo
For Each singleFile In allFiles
'ds.ReadXml(singleFile)
xd.Load(singleFile.FullName)
Dim nodes As XmlNodeList = xd.DocumentElement.SelectNodes("/ORDER/ORDER_HEADER")
Dim ORDER_NO As String = " "
For Each node As XmlNode In nodes
If Not node.SelectSingleNode("ORDER_NO") Is Nothing Then
ORDER_NO = node.SelectSingleNode("ORDER_NO").InnerText
End If
Next
Next

Related

How to remove extra line feeds within double quoted fields

Newbie here. Code below removes ALL line feeds in my file but it also removes EOR line feeds. Can somebody please help me how to fix code below so it only removes extra line feeds within double quoted fields? Any help will be greatly appreciated. Thanks
Public Sub Main()
'
Dim objReader As IO.StreamReader
Dim contents As String
objReader = New IO.StreamReader("testfile.csv")
contents = objReader.ReadToEnd()
objReader.Close()
Dim objWriter As New System.IO.StreamWriter("testfile.csv")
MsgBox(contents)
'contents = Replace(contents, vbCr, "")
contents = Replace(contents, vbLf, "")
MsgBox(contents)
objWriter.Write(contents)
objWriter.Close()
'
Dts.TaskResult = ScriptResults.Success
End Sub
I forgot to mention that the input file name changes daily, How do I code so it doesn't care for the file name as long as it as a CSV file? So testfile name has current date and changes daily. I've tried just the file path and it errored out as well. Used the *.csv and it didnt like that either.
objReader = New IO.StreamReader("\FolderA\FolderB\TestFile09212022.csv")
If you are sure there are no double quotes text inside the double quotes you can do it like this:
Dim sNewString As String = ""
Dim s As String
Dim bFirstQuoted As Boolean = False
Dim i As Integer
Dim objWriter As New System.IO.StreamWriter("testfile.csv")
MsgBox(contents)
For i = 1 To contents.Length
s = Mid(contents, i, 1)
If s = """" Then bFirstQuoted = Not bFirstQuoted
If Not bFirstQuoted OrElse (s <> vbLf AndAlso bFirstQuoted) Then
sNewString += s
else
sNewString += " "
End If
Next
MsgBox(sNewString )
objWriter.Write(sNewString )
objWriter.Close()
Dts.TaskResult = ScriptResults.Success

How to combine all csv files from the same folder into one data

I want merge multiple csv files with same layout from the same folder
example :
csv1.csv
ID, PINA,PINB,PCS
1,100,200,450
2,99,285,300
csv2.csv
ID, PINA,PINB,PCS
1,100,200,999
2,99,285,998
out.csv (The file I want make by VB.net)
ID, PINA,PINB,PCS,PCS
1,100,200,450,999
2,99,285,300,998
my problem code :
Dim FileReader As StreamReader
Dim i As Integer = 0
Dim temp As String
For i = 0 To LstFiles.Items.Count - 1
FileReader = File.OpenText(LstFiles.Items.Item(i))
temp = FileReader.ReadToEnd
File.AppendAllText(SaveFileDialog1.FileName, temp)
Next
Please guide me.
Thanks a lot !
Looks to me like each line in the input files has an identifier based on the first value in that row. You want to combine all the numbers after that identifier, from all the files in your ListBox, into one list of numbers that is sorted and has no duplicates. Then you want to generate an output file that has all those identifiers followed by each set of sorted, unique numbers.
If that is correct, then try this out:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
Dim header As String = ""
Dim combinedLines As New SortedList(Of Integer, List(Of Integer))
For Each filename As String In LstFiles.Items
Dim lines = File.ReadLines(filename)
If header = "" Then
header = lines.First
End If
lines = lines.Skip(1)
For Each line As String In lines
Dim strValues = line.Split(",").AsEnumerable
Try
Dim lineNumber As Integer = Integer.Parse(strValues.First)
strValues = strValues.Skip(1)
Dim numbers = strValues.ToList.ConvertAll(Of Integer)(Function(x) Integer.Parse(x))
If Not combinedLines.ContainsKey(lineNumber) Then
combinedLines.Add(lineNumber, New List(Of Integer)(numbers))
Else
combinedLines(lineNumber).AddRange(numbers)
End If
Catch ex As Exception
MessageBox.Show("Error Parsing Line: " & line)
End Try
Next
Next
Using sw As New StreamWriter(SaveFileDialog1.FileName, False)
sw.WriteLine(header)
For Each numberSet In combinedLines
Dim numbers = numberSet.Value.Distinct.ToList
numbers.Sort()
sw.WriteLine(numberSet.Key & "," & String.Join(",", numbers))
Next
End Using
End If
End Sub

Placement of constructor

For Some reason in the following segment in my for each statment its declaring the that the csv data cant be null even though as you see their when i create the csvData Object is its created within the loop is that the correct placement.
For Each thisDocument As String In documentList
filename = Path.GetFileName(thisDocument)
SiteId = filename.Substring(0, filename.IndexOf("_"))
Dim orderNumbers As String()
Dim csvData As New DataTable
Dim importUtils As New ImportController
filename = Path.GetFileName(thisDocument)
orderNumbers = filename.Split("_")
location = filename.Substring(0, 3)
importUtils = New ImportController(cfb.TargetFolder & filename)
csvData = importUtils.ConvertCsvToDatatable(True)
ImportDataTableToSql(cfb.TargetFolder & filename, csvData, cfb.StoreCompany)
Next
edits to show convertcsvtodatatable()
Public Function ConvertCsvToDatatable(ByVal ColumnNames As Boolean) As DataTable
Try
Dim dt As New DataTable
For Each columnName In GetColumnsfromCsv(ColumnNames, ",")
dt.Columns.Add(columnName)
Next
Dim fileReader As New StreamReader(FileName)
If ColumnNames Then
fileReader.ReadLine()
End If
Dim line As String = fileReader.ReadLine
While Not IsNothing(line)
line = line.Replace(Chr(34), "")
dt.Rows.Add(line.Split(","))
line = fileReader.ReadLine
End While
fileReader.Close()
Return dt
Catch ex As Exception
'log to file
End Try
Return Nothing
End Function

Reading Text line by line to make string manipulation

So to start this is the code I have already written:
Dim MyFile As String = "Path"
Dim str_new As String
Dim str_old As String = File.ReadAllText(MyFile)
Dim sr As New StreamReader(MyFile)
Dim strLines As String() = Strings.Split(sr.ReadToEnd, Environment.NewLine)
Dim Character As Integer = 5 'Line 1 always has 5 characters
For i = 2 To strLines.Length
Dim PreviousLine As String = sr.ReadLine(i - 1)
Dim CurrentLine As String = sr.ReadLine(i)
If CurrentLine.Contains(TextBox1.Text / 100) Then
If PreviousLine.Contains("divide") Then
Exit For
End If
End If
Character = Character + CurrentLine.Length
Next
sr.Close()
str_new = Replace(str_old, (TextBox1.Text / 100), (TextBox3.Text / 100), Character, 1)
Dim objWriter3 As New System.IO.StreamWriter(MyFile, False)
objWriter3.Write(str_new)
objWriter3.Flush()
objWriter3.Close()
I am trying to figure out a way to break a long code file into lines then check each line for certain strings. If the current line contains the string then I will do additional check on above and/or below lines to make sure This is the correct instance of the string. Finally I want to replace just that instance of the string with a different string.
An example: text file
class
...
0.3
divide <-- Previous Line
0.3 <-- TextBox1.Text is 30
.5
end
I want the code to go past the first instance of 0.3
Find the second instance
Check previous line for divide
Exit Loop
Replace second instance of 0.3 to some value
I have been looking into this for a while now and any help would be greatly appreciated!
~Matt
Revised: Code
Dim MyFile As String = "Path"
Dim NewFile As String = "Temporary Path"
Dim PreviousLine As String = ""
Dim CurrentLine As String = ""
Using sr As StreamReader = New StreamReader(MyFile)
Using sw As StreamWriter = New StreamWriter(NewFile)
CurrentLine = sr.ReadLine
Do While (Not CurrentLine Is Nothing)
Dim LinetoWrite = CurrentLine
If CurrentLine.Contains(TextBox1.Text) Then
If PreviousLine.Contains("divide") Then
LinetoWrite = Replace(CurrentLine, TextBox1.Text, TextBox3.Text)
End If
End If
sw.WriteLine(LinetoWrite)
PreviousLine = CurrentLine
CurrentLine = sr.ReadLine
Loop
End Using
End Using
My.Computer.FileSystem.CopyFile(NewFile, MyFile, True)
You are facing the problem in the wrong way. You have to set both, reader and writer, and generate a new file with all the modifications. Your code has various parts which should be improved; in this answer, I am just showing how to use StreamReader/StreamWriter properly. Sample code:
Dim MyFile As String = "input path"
Dim OutputFile As String = "output path"
Dim PreviousLine As String = ""
Dim CurrentLine As String = ""
Using sr As StreamReader = New StreamReader(MyFile)
Using sw As StreamWriter = New StreamWriter(OutputFile)
CurrentLine = sr.ReadLine
Do While (Not CurrentLine Is Nothing)
Dim lineToWrite = CurrentLine
'Perform the analysis you wish by involving the current line, the previous one and as many other (previous) lines as you wish; and store the changes in lineToWrite. You should call a function here to perform this analysis
sw.WriteLine(lineToWrite) 'Writing lineToWrite to the new file
PreviousLine = CurrentLine 'Future previous line
CurrentLine = sr.ReadLine 'Reading the line for the next iteration
Loop
End Using
End Using

How to read duplicate string in a text file in vb.net

I want this program to open a text file and find those specific character and add the words after that into the list (each character has specific subitem in the list).
It work well if there is no duplication. But if I have list like:
/* First row of the list */
#Alireza
%Human
&1
#$1200
$*1
*$1000
/* ' Second row */
#Behzad
%Human
&1
#$1340
$*1
*$1000
/* ' And third row */
#Samaneh
%Human
&1
#$1570
$*1
*$1230
then it only add the first row. I also make a while loop but it will only add first row to other rows. Is there anyone can help please!(by the way my list include 6 columns )
this is the code:
Public code As String
Public cat As String
Public stock As Integer
Public price As Double
Public sold As Double
Public cost As Double
Public i As Integer
Public Sub _Load(ByVal FileName As String)
Dim strLines() As String
Dim strLine As String
Dim strData As String
Dim objFileInfo As New FileInfo(FileName)
strData = My.Computer.FileSystem.ReadAllText(FileName)
strLines = strData.Split(New String() {ControlChars.CrLf}, StringSplitOptions.RemoveEmptyEntries)
For Each strLine In strLines
If strLine.StartsWith("#") Then
code = strLine.Substring(1)
End If
strLine = Nothing
Next
For Each strLine In strLines
If strLine.StartsWith("%") Then
cat = strLine.Substring(1)
Exit For
End If
strLine = Nothing
Next
For Each strLine In strLines
If strLine.StartsWith("&") Then
stock = strLine.Substring(1)
Exit For
End If
strLine = Nothing
Next
For Each strLine In strLines
If strLine.StartsWith("#$") Then
price = strLine.Substring(2)
Exit For
End If
strLine = Nothing
Next
For Each strLine In strLines
If strLine.StartsWith("$*") Then
sold = strLine.Substring(2)
Exit For
End If
strLine = Nothing
Next
For Each strLine In strLines
If strLine.StartsWith("*$") Then
cost = strLine.Substring(2)
Exit For
End If
strLine = Nothing
Next
End Sub
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles toolImport.Click
Dim ans As String
OpenFileDialog1.Title = "What are you looking for?"
OpenFileDialog1.InitialDirectory = Application.StartupPath
OpenFileDialog1.Filter = "text Files (*.txt)|*.txt|Data Files (*.dat)|*.dat|All files (*.*)|*.*"
OpenFileDialog1.FileName = "myList"
Try
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim sr As StreamReader = New StreamReader(OpenFileDialog1.FileName)
Do While sr.Peek > -1
_Load(OpenFileDialog1.FileName)
Dim list As New ListViewItem(code)
list.SubItems.Add(cat)
list.SubItems.Add(stock)
list.SubItems.Add(price)
list.SubItems.Add(sold)
list.SubItems.Add(cost)
listClothes.Items.Add(list)
i += 1
MessageBox.Show("Your list has been uploaded successfully", "ccc!", MessageBoxButtons.OK, MessageBoxIcon.Information)
Loop
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
By "duplicate strings", I think you mean how to read the file when there is more than one item (group of 6 columns) in the file.
The reason your current program is getting only the first item is because you're exiting the For loop after you find the first occurrence of a given sub item, regardless of how many there may be in the file.
One way to resolve this is to change your sub _Load to a function and have it return a List(Of ListViewItem) object, which you could then iterate through and add to the master list (ListClothes). I would also get rid of the StreamReader, as you don't need it for what you are doing. You're passing the FileName property (which contains the path and extensions) from the OpenFileDialog, so you can simply use that in the _Load function.
It would look something like this:
Public Function _Load(ByVal FileName As String) As List(Of ListViewItem)
Dim Lines() As String
Dim List(Of ListViewItem) StockList = New List(Of ListViewItem)
Dim ListViewItem As StockItem
Lines = File.ReadAllText(FileName).Split(New String() _
{ ControlChars.CrLf}, StringSplitOptions.RemoveEmptyEntries)
For j = 0 To Lines.Length - 1 Step 6
StockItem = New ListViewItem(Lines(j))
StockItem.SubItems.Add(Lines(j + 1))
StockItem.SubItems.Add(Lines(J + 2))
StockItem.SubItems.Add(Lines(j + 3))
StockItem.SubItems.Add(Lines(J + 4))
StockItem.SubItems.Add(Lines(j + 5))
StockList.Add(StockItem)
Next
Return StockList
End Function
The above code takes the passed in FileName, does a split on the string returned from ReadAllText and removes empty entries.
Next it loops through code, 6 lines at a time. In the loop a new ListViewItem is created, and the sub items are populated, and then this ListViewItem is added to the List(Of ListViewItem).
The populated StockList is then returned.
In your button1_Click event, you could use it like this:
Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles toolImport.Click
Dim ans As String
Dim stockItems As List(Of ListViewItem)
OpenFileDialog1.Title = "What are you looking for?"
OpenFileDialog1.InitialDirectory = Application.StartupPath
OpenFileDialog1.Filter = "text Files (*.txt)|*.txt|Data Files (*.dat)|*.dat|All files (*.*)|*.*"
OpenFileDialog1.FileName = "myList"
Try
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
stockItems = _Load(OpenFileDialog1.FileName)
For Each (stockItem As ListViewItem in stockItems)
listClothes.Add(stockItem)
Next
MessageBox.Show("Your list has been uploaded successfully", "ccc!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
In this code, you pass the selected FileName to the _Load method and assign its return value to the local stockItems variable.
Then you loop through the stockItems list, and add each ListViewItem in it to your clothesList.
NOTE that this code is brittle - if the columns are not in the correct order in the input file, or if a column(s) is/are missing, your data will be skewed, and the program could potentially crash if you try to read a line in the array (from the file) that doesn't exist. Of course, you can wrap that code in a Try Catch block as well.
This is merely one way to do it - I have no doubt there are others. But this should at least get you going in the right direction.
EDIT
The easiest way to remove the leading characters is to add them to the split, like this:
Lines = File.ReadAllText(FileName).Split(New String() _
{ ControlChars.CrLf, "#", "%", "&", "#$", "$*", "*$"}, _
StringSplitOptions.RemoveEmptyEntries)
This will return an array of all the lines, minus empty lines and the leading characters.
Of course, with the code above, you actually don't need those leading characters anymore, as long as the input file always has the columns in the same order.