check if each line from a text file startwith certain character - vb.net

Dim reader As StreamReader = New StreamReader("C:\Users\S160358\Desktop\file.txt")
Do While reader.Peek() > -1
Dim line As String = reader.ReadLine()
If line.EndsWith("PSTAT") Then
Console.WriteLine("Yes")
Console.ReadLine()
Else
Console.WriteLine("No")
Console.ReadLine()
End If
Loop
Sample data
1111111111|22222222222222|3333333333|PSTAT
2222222222|33333333333333|
1111111111|PSTAT
AAAAAAAAAA|DDDDDDDDDDDDDD|FFFFFFFFFF|PSTAT
I am trying to check if any of line not end with certain characters. If it return "No" then it will process a reformatting function. After I run this code, it will return "Yes", and it should return "No" as second row is not end with PSTAT.

If you want to check all the lines, then you can't determine the result until you have checked all the lines (or found a line without the ending):
Dim reader As StreamReader = New StreamReader("C:\Users\S160358\Desktop\file.txt")
Dim anyNo As Boolean = False
Do While reader.Peek() > -1
Dim line As String = reader.ReadLine()
If Not line.EndsWith("PSTAT") Then
anyNo = True
Exit Do
End If
Loop
If anyNo Then
Console.WriteLine("No")
Else
Console.WriteLine("Yes")
End If
Console.ReadLine()
Or simply:
Dim anyNo As Boolean = _
File.ReadAllLines("C:\Users\S160358\Desktop\file.txt") _
.Any(Function(line) Not line.EndsWith("PSTAT"))
If anyNo Then
Console.WriteLine("No")
Else
Console.WriteLine("Yes")
End If
Console.ReadLine()

Related

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in vb.net CSV program

This program is simply reading from a CSV and putting that into a DatagridView table. I am not sure what is causing the error shown below.
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in Minecraft Server Program.exe"
This error points to the line "newrow("Days_remaining") = columns(1)
Also, the CSV is formatted as such:
xX_EpicGamer_Xx,2,2/05/2021,9,6,Player was mean to others and stole lots of diamonds
pewdiepie,3,2/05/2021,4,2,Player swore
Thank you for any help
Public Sub LoadCSVFile()
'If the Input file cannot be found, then give error message And exit this Subroutine.
If Not File.Exists(BansCSVFile) Then
MsgBox("Input CSV File of Item Prices not found: " & BansCSVFile)
Exit Sub
End If
'Set up streamreader and variables for reading through file
Dim srdCSV As New IO.StreamReader("bans.csv", System.Text.Encoding.Default)
Dim sline As String = ""
Do
'Read through each line, separating with the comma and putting each entry into its respective column
sline = srdCSV.ReadLine
If sline Is Nothing Then Exit Do
Dim columns() As String = sline.Split(",")
Dim newrow As DataRow = datatable1.NewRow
newrow("Player") = columns(0)
newrow("Days_remaining") = columns(1)
newrow("Date_started") = columns(2)
newrow("Timespan") = columns(3)
newrow("Rule_broken") = columns(4)
newrow("Extra_info") = columns(5)
datatable1.Rows.Add(newrow)
Loop
srdCSV.Close()
dgvBans.DataSource = datatable1
Me.Text = datatable1.Rows.Count & "rows"
End Sub
Edit:
This new code fixed the issue.
Public Sub LoadCSVFile()
'If the Input file cannot be found, then give error message And exit this Subroutine.
If Not File.Exists(BansCSVFile) Then
MsgBox("Input CSV File of Item Prices not found: " & BansCSVFile)
Exit Sub
End If
'Set up streamreader and variables for reading through file
srdCSV = New IO.StreamReader("bans.csv")
Dim totalrec As Integer = 0
Try
Do Until srdCSV.Peek = -1
'Read through each line, separating with the comma and putting each entry into its respective column
strInputFileLine = srdCSV.ReadLine()
'Split CSV lines where commas are
Dim RecordLineColumns() As String = strInputFileLine.Split(",")
'Create a new row in data table and place data into it from array
Dim newrow As DataRow = datatable1.NewRow
newrow("Player") = RecordLineColumns(0)
newrow("Days_remaining") = RecordLineColumns(1)
newrow("Date_started") = RecordLineColumns(2)
newrow("Timespan") = RecordLineColumns(3)
newrow("Rule_broken") = RecordLineColumns(4)
newrow("Extra_info") = RecordLineColumns(5)
datatable1.Rows.Add(newrow)
totalrec = totalrec + 1
Loop
Catch ex As Exception
MsgBox("Error reading file")
Exit Sub
End Try
srdCSV.Close()
'Me.Text = datatable1.Rows.Count & "rows"
MsgBox("Total input records = " & totalrec)
End Sub
using the Try/Catch syntax
After checking which column has a problem, try verifying the csv file.
I am guessing that the Extra_Info is not necessarily present for every record. I am checking for a length less 5 and exiting but if it has at least 5 we continue but only fill in the last field if the length is 6.
Public Sub LoadCSVFile(BansCSVFile As String)
Dim datatable1 As New DataTable
With datatable1.Columns
.Add("Player")
.Add("Days_remaing")
.Add("Date_started")
.Add("Timespan")
.Add("Rule_broken")
.Add("Extra_Info")
End With
If Not File.Exists(BansCSVFile) Then
MsgBox("Input CSV File of Item Prices not found: " & BansCSVFile)
Exit Sub
End If
Dim lines = File.ReadAllLines(BansCSVFile)
For Each sline In lines
Dim columns() As String = sline.Split(","c)
If columns.Length < 5 Then
MessageBox.Show($"Incomplete data on line {sline}")
Return
End If
Dim newrow As DataRow = datatable1.NewRow
newrow("Player") = columns(0)
newrow("Days_remaining") = columns(1)
newrow("Date_started") = columns(2)
newrow("Timespan") = columns(3)
newrow("Rule_broken") = columns(4)
If columns.Length = 6 Then
newrow("Extra_info") = columns(5)
End If
datatable1.Rows.Add(newrow)
Next
dgvBans.DataSource = datatable1
Me.Text = datatable1.Rows.Count & "rows"
End Sub

IOException was unhandled "The process cannot access the file

I am trying to reading the file, reformat some rows, then overwrite the file line by line.
I know the problem is cause by opening the existing file twice, but I don't know how to fix it.
Public Sub Main()
Dim objStreamReader As StreamReader
Dim objWriter As StreamWriter
If Dts.Variables("File").Value.ToString.Length > 0 Then
'read the file
objStreamReader = New StreamReader(Dts.Variables("File").Value.ToString)
'write the file
objWriter = New StreamWriter(Dts.Variables("File").Value.ToString)
'read file line by line
Dim row, line As String
Dim isFirstRow As Boolean = True
Dim numColumns As Integer = 0
row = ""
Do While objStreamReader.Peek() <> -1
line = objStreamReader.ReadLine() 'read a line
If line.Trim() = "" Then
Continue Do 'skip blank line
End If
If isFirstRow Then 'first line in the file (it's always a complete row)
numColumns = CountNumColumns(line) 'record the number of columns
isFirstRow = False
objWriter.WriteLine(line)
ElseIf CountNumColumns(line) = numColumns Then
'the line is a complete row
objWriter.WriteLine(line)
Else
row = row & line
If CountNumColumns(row) = numColumns Then
'we have a complete row
objWriter.WriteLine(row)
row = ""
End If
End If
Loop
'close files
objStreamReader.Close()
objWriter.Close()
End If
Dts.TaskResult = ScriptResults.Success
End Sub
'Counts the number of columns in a given line
Function CountNumColumns(ByVal line As String) As Integer
Dim count As Integer = 0
For index As Integer = 0 To line.Length - 1
If line(index) = "|" Then
count = count + 1
End If
Next
Return count
End Function

Loop through the lines of a text file in 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

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

VB.NET For Each

After finally fixing my last problem, the code that I ended with was
Function MD5(ByVal strToHash As String) As String
Dim md5Obj As New Security.Cryptography.MD5CryptoServiceProvider
Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
bytesToHash = md5Obj.ComputeHash(bytesToHash)
Dim strResult As String = ""
For Each b As Byte In bytesToHash
strResult += b.ToString("x2")
Next
Return strResult
End Function
Dim words As IEnumerable(Of String) = File.ReadLines(OpenFileDialog1.FileName)
For Each word As String In words
If String.Equals(MD5(word), hash.Text) Then
Label2.Text = word
Else : Label2.Text = "Hash Could Not Be Cracked"
End If
Next
Now I need to make it stop once the hashed word matches the hash I typed in!
To stop a loop, use Exit For:
Dim words As IEnumerable(Of String) = File.ReadLines(OpenFileDialog1.FileName)
For Each word As String In words
If MD5(word) = hash.Text Then
Label2.Text = word
Exit For
Else : Label2.Text = "Hash Could Not Be Cracked"
End If
Next
But note that the Else makes no sense here (the form won’t be updated until after the method is left) and that String.Equals can be replaced here by = (I’ve already done that).
You could use LINQ's FirstOrDefault, since you're using ReadLines instead of ReadAllLines anyway:
Dim firstWord = (From line In IO.File.ReadLines(OpenFileDialog1.FileName)
Where String.Equals(MD5(line), hash.Text)).FirstOrDefault()
If firstWord IsNot Nothing Then
Label2.Text = firstWord
Else
Label2.Text = "Hash Could Not Be Cracked"
End If
Another way is a simple loop:
Dim lines = IO.File.ReadAllLines(OpenFileDialog1.FileName)
Dim matchingLine As String = Nothing
For i = 0 To lines.Length -1
Dim line = lines(i)
If String.Equals(MD5(line), hash.Text)) Then
matchingLine = line
Exit For
End If
Next
If matchingLine IsNot Nothing Then
Label2.Text = matchingLine
Else
Label2.Text = "Hash Could Not Be Cracked"
End If