VB read line by line, compare a value and extract portion to display - vb.net

I have a text file on drive C:, I need to open and read the first line and do the code to display, then read second line and do same, etc. etc. until it reads all the lines in the text file.
Not sure how to do it...
My code
I think I figure it out, below, BUT how do i do that For EACH line of the text file, meaning, apply the same evaluation per line?
'type of message triggers
Dim type1 As String = "d1err./"
Dim type2 As String = "d1jam./"
Dim type3 As String = "d1spe./"
Dim type4 As String = "d2err./"
Dim type5 As String = "d2jam./"
Dim type6 As String = "d2spe./"
Dim fileReader As StreamReader = My.Computer.FileSystem.OpenTextFileReader("C:\A\data\display.txt")
Dim stringReader As String = fileReader.ReadLine()
While stringReader <> Nothing
Dim LineStart As String = stringReader.Substring(0, 7)
Dim RestOfLine As String = stringReader.Substring(7)
If LineStart = type1 Then
Display1.Dis1RTB1.Clear()
Display1.Dis1RTB1.Text = RestOfLine
ElseIf LineStart = type2 Then
Display1.Dis1RTB2.Clear()
Display1.Dis1RTB2.Text = RestOfLine
ElseIf LineStart = type3 Then
Display1.Dis1RTB3.Clear()
Display1.Dis1RTB3.Text = RestOfLine
ElseIf LineStart = type4 Then
Display2.Dis2RTB1.Clear()
Display2.Dis2RTB1.Text = RestOfLine
ElseIf LineStart = type5 Then
Display2.Dis2RTB2.Clear()
Display2.Dis2RTB2.Text = RestOfLine
ElseIf LineStart = type6 Then
Display2.Dis2RTB3.Clear()
Display2.Dis2RTB3.Text = RestOfLine
End If
stringReader = fileReader.ReadLine()
End While
fileReader.Close()
End Sub

Maybe this will help you
Public Class Form1
Dim fileReader As New IO.StreamReader("C:\Users\User\Desktop\New Text Document.txt")
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not fileReader.EndOfStream Then
TextBox1.Text += fileReader.ReadLine & vbNewLine
End If
'Or you could do it like this
While Not fileReader.EndOfStream
Dim tmpStr As String = fileReader.ReadLine
Select Case tmpStr
Case "Dis1err"
'Do Work here
End Select
End While
End Sub
End Class

Related

How to check if new line is empty in richtextbox

I am checking if a line in richtextbox is empty. If not, it will go at the next line.
The code I am using is:
Dim text as string="hello"
Dim lines = RichTextBox1.Lines
Dim upperBound = lines.GetUpperBound(0)
If lines(upperBound).Trim() = String.Empty Then
lines(upperBound) = text
RichTextBox1.Lines = lines
Else
RichTextBox1.AppendText(Environment.NewLine & text)
End If
Which is working perfectly. But just now I discovered that if Richtextbox1 is completely empty, this code will not add text to it. Is there any way to fix this little bug? Thanks
See if this does what you want:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim text As String = "hello"
If RichTextBox1.Text.Trim = "" Then
RichTextBox1.AppendText(titolo)
ElseIf RichTextBox1.Lines(RichTextBox1.Lines.GetUpperBound(0)).Length = 0 Then
RichTextBox1.AppendText(titolo)
ElseIf RichTextBox1.Lines(RichTextBox1.Lines.GetUpperBound(0)).Trim = "" Then
Dim lines = RichTextBox1.Lines
lines(lines.GetUpperBound(0)) = titolo
RichTextBox1.Lines = lines
Else
RichTextBox1.AppendText(Environment.NewLine & text)
End If
End Sub
You can try this very efficient system.
This is called LinQ for array, You can query an array for a empty line,
if the count is greater than 0 then exit(or give an error)
Dim text As String = "hello"
Dim lines = RichTextBox1.Lines
Dim qry = From n In lines
Where n = ""
Select n
If qry.Count > 0 Then
'you can give some error here
End If
Try:
Dim text as string="hello"
Dim lines = RichTextBox1.Lines
Dim empty = {""}
If lines.Length = 0 Then lines = empty
Dim upperBound = lines.GetUpperBound(0)
If lines(upperBound).Trim() = String.Empty Then
lines(upperBound) = titolo
RichTextBox1.Lines = lines
Else
RichTextBox1.AppendText(Environment.NewLine & text)
End If

vb.net readalllines fill form replace certain lines coding advice

What I'm trying to accomplish is reading a text file and selecting certain lines to modify by filling in text from a second form. Here is an example the code I'm currently using. What's happening is I'm looking for a line that starts with 718 and then somewhere after that line there will be a line that starts with 720. I need both lines to fill in the second form. The only way I can think of is to just keep adding 1 to the line until it reaches the line I need. I'm still new to this and I'm sure there's an easier way to do this maybe using Try or While but I'm not sure how. Appreciate any help.
Dim lines() As String = File.ReadAllLines(tempsave)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("718") Then
If lines(i + 1).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 1).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array(3), FormFill.TextBox1.Text)
lines(i + 1) = lines(i + 1).Replace(array(9), FormFill.TextBox2.Text)
Else
If lines(i + 2).StartsWith("720") Then
Dim array() As String = lines(i).Split("*"c, "~"c)
Dim array2() As String = lines(i + 2).Split("*"c, "~"c)
FormFill.TextBox1.Text = array(3)
FormFill.TextBox2.Text = array(9)
FormFill.ShowDialog()
lines(i) = lines(i).Replace(array2(3),FormFill.TextBox1.Text)
lines(i + 2) = lines(i + 2).Replace(array(9), FormFill.TextBox2.Text)
End If
End If
End If
Next
Example Data:
Input:
123*test*test*test~
718*test*test*test~
543*test*test*test~
720*test*test*test~
Output:
123*test*test*test~
718*test*test*newdata~
543*test*test*test~
720*test*test*newdata~
Here, try this:
Public Sub Lines()
Dim _
aNextLines,
aAllLines As String()
Dim _
s718Line,
s720Line As String
aAllLines = IO.File.ReadAllLines("D:\Logs\Data.log")
For i As Integer = 0 To aAllLines.Length - 1
If aAllLines(i).StartsWith("718") Then
s718Line = aAllLines(i)
aNextLines = aAllLines.Skip(i + 1).ToArray
s720Line = aNextLines.FirstOrDefault(Function(Line) Line.StartsWith("720"))
' Process data here
End If
Next
End Sub
--UPDATE--
Here's a modified version that both reads and writes:
Public Sub Lines()
Dim oForm As FormFill
Dim _
aNextLines,
aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
oForm = New FormFill
aAllLines = IO.File.ReadAllLines(oForm.FilePath)
s718Line = String.Empty
s720Line = String.Empty
For i718Index = 0 To aAllLines.Length - 1
If aAllLines(i718Index).StartsWith("718") Then
s718Line = aAllLines(i718Index)
aNextLines = aAllLines.Skip(i718Index + 1).ToArray
For i720Index = 0 To aNextLines.Length - 1
If aNextLines(i720Index).StartsWith("720") Then
s720Line = aNextLines(i720Index)
Exit For ' Assumes only one 720 line in the file
End If
Next
Exit For ' Assumes only one 718 line in the file
End If
Next
oForm.TextBox718.Text = s718Line
oForm.TextBox720.Text = s720Line
oForm.TextBox718.Tag = i718Index
oForm.TextBox720.Tag = i720Index
End Sub
Now, in your Save button's Click event handler:
Private Sub SaveButton_Click(Sender As Button, e As EventArgs) Handles SaveButton.Click
Dim aAllLines As String()
Dim _
i718Index,
i720Index As Integer
Dim _
s718Line,
s720Line As String
s718Line = Me.TextBox718.Text
s720Line = Me.TextBox720.Text
i718Index = Me.TextBox718.Tag
i720Index = Me.TextBox720.Tag
aAllLines = IO.File.ReadAllLines(Me.FilePath)
aAllLines(i718Index) = s718Line
aAllLines(i720Index) = s720Line
IO.File.WriteAllLines(Me.FilePath, aAllLines)
End Sub
That should do it.

Reading and writing from a csv file

Structure TownType
Dim Name As String
Dim County As String
Dim Population As Integer
Dim Area As Integer
End Structure
Sub Main()
Dim TownList As TownType
Dim FileName As String
Dim NumberOfRecords As Integer
FileName = "N:\2_7_towns(2).csv"
FileOpen(1, FileName, OpenMode.Random, , , Len(TownList))
NumberOfRecords = LOF(1) / Len(TownList)
Console.WriteLine(NumberOfRecords)
Console.ReadLine()
There are only 12 records in the file but this returns a value of 24 for number of records. How do I fix this?
Contents of csv file:
Town, County,Pop, Area
Berwick-upon-tweed, Nothumberland,12870,468
Bideford, devon,16262,430
Bognor Regis, West Sussex,62141,1635
Bridlington, East Yorkshire,33589,791
Bridport, Dorset,12977,425
Cleethorpes, Lincolnshire,31853,558
Colwyn bay, Conway,30269,953
Dover, Kent,34087,861
Falmouth, Cornwall,21635,543
Great Yarmouth, Norfolk,58032,1467
Hastings, East Sussex,85828,1998
This will read the contents into a collection and you can get the number of records from the collection.
Sub Main()
Dim FileName As String
Dim NumberOfRecords As Integer
FileName = "N:\2_7_towns(2).csv"
'read the lines into an array
Dim lines As String() = System.IO.File.ReadAllLines(FileName)
'read the array into a collection of town types
'this could also be done i a loop if you need better
'parsing or error handling
Dim TownList = From line In lines _
Let data = line.Split(",") _
Select New With {.Name = data(0), _
.County = data(1), _
.Population = data(2), _
.Area = data(3)}
NumberOfRecords = TownList.Count
Console.WriteLine(NumberOfRecords)
Console.ReadLine()
End Sub
Writing to the console would be accomplished with something like:
For Each town In TownList
Console.WriteLine(town.Name + "," + town.County)
Next
Many ways to do that
Test this:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
dim FileName as string = "N:\2_7_towns(2).csv"
Dim Str() As String = System.IO.File.ReadAllLines(filename)
'Str(0) contains : "Town, County,Pop, Area"
'Str(1) contains : "Berwick-upon-tweed, Nothumberland,12870,468"
'Str(2) contains : "Bideford, devon,16262,430"
' etc...
'Sample code for string searching :
Dim Lst As New List(Of String)
Lst.Add(Str(0))
Dim LookingFor As String = "th"
For Each Line As String In Str
If Line.Contains(LookingFor) Then Lst.Add(Line)
Next
Dim Result As String = ""
For Each St As String In Lst
Result &= St & Environment.NewLine
Next
MessageBox.Show(Result)
'Sample code creating a grid :
Dim Grid = New DataGridView
Me.Controls.Add(Grid)
Grid.ColumnCount = Str(0).Split(","c).GetUpperBound(0) + 1
Grid.RowCount = Lst.Count - 1
Grid.RowHeadersVisible = False
For r As Integer = 0 To Lst.Count - 1
If r = 0 Then
For i As Integer = 0 To Lst(r).Split(","c).GetUpperBound(0)
Grid.Columns(i).HeaderCell.Value = Lst(0).Split(","c)(i)
Next
Else
For i As Integer = 0 To Lst(r).Split(","c).GetUpperBound(0)
Grid(i, r - 1).Value = Lst(r).Split(","c)(i)
Next
End If
Next
Grid.AutoResizeColumns()
Grid.AutoSize = True
End Sub

how to use componentone c1printdocument in asp.net for reading text file and convert into pdf with format?

I am using the C1PrintDocument class to read a text file and convert into pdf in web. Actually it converts into pdf but without the format as like in text file.
For eg. I have a text file which has only one page. But it makes into two pages while convert into pdf. Below is the code what I use.
Imports System.IO
Imports C1.C1Preview
Imports C1.C1Pdf
Imports C1.Web.Wijmo.Controls.C1ReportViewer
Imports System.Runtime.Serialization.Formatters.Binary
Imports C1.C1Pdf.PdfDocumentInfo
Imports C1.C1Preview.C1PrintDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Try
Dim strmappath As String = System.Web.HttpContext.Current.Server.MapPath("~")
Dim filename As String
filename = Path.Combine(Server.MapPath("~"), "12214.txt")
Dim sr As New System.IO.StreamReader(filename, System.Text.Encoding.UTF8)
Dim str As [String] = sr.ReadToEnd()
Dim doc1 As C1PrintDocument = C1ReportViewer.CreateC1PrintDocument()
Dim doc As New C1PrintDocument
doc.Pages(1).PageSettings.TopMargin = 0
doc.Pages(1).PageSettings.LeftMargin = 0
doc.Pages(1).PageSettings.RightMargin = 0
doc.StartDoc()
Dim overlay As New RenderArea()
overlay.Width = "100%"
overlay.Height = "100%"
overlay.Style.Borders.All = LineDef.Default
doc.PageLayout.Overlay = overlay
Dim lines As String() = System.IO.File.ReadAllLines(filename)
Dim linecnt As Integer = System.IO.File.ReadLines(filename).Count
Dim strpages1 As String()
ReDim strpages1(Math.Abs(linecnt / 66) - 1)
Dim intcnt As Integer
Dim intlinereadcnt As Integer
intlinereadcnt = 0
intcnt = 0
intlinereadcnt = 0
For Each line In lines
If intcnt <= 66 Then
If intcnt <> 66 Then
strpages1(intlinereadcnt) = strpages1(intlinereadcnt) &
line & vbCrLf
End If
intcnt = intcnt + 1
ElseIf intcnt = 67 Then
intlinereadcnt = intlinereadcnt + 1
intcnt = 0
End If
Next
Dim strPages As String() = str.Split(Chr(12))
Dim strPage As String = String.Empty
Dim txtPage As New C1.C1Preview.RenderText(doc)
With doc
.AllowNonReflowableDocs = True
For Each strPage In strpages1
If strPage.Length > 0 Then
txtPage.Text = strPage
txtPage.X = 150
doc.Style.TextColor = Drawing.Color.Blue
.RenderBlockText(txtPage.Text)
.Style.WordWrapMode = False
.NewPage()
End If
Next
End With
Dim m_pdfExporter As C1.C1Preview.Export.PdfExporter
m_pdfExporter = C1.C1Preview.Export.ExportProviders.
PdfExportProvider.NewExporter()
m_pdfExporter.Document = doc
m_pdfExporter.Export(Server.MapPath("~") & "12214" & ".pdf")
Dim sr2 As System.IO.MemoryStream
sr2 = New MemoryStream
doc.Save(sr2)
Dim biteArray As Byte() = New Byte(sr2.Length - 1) {}
sr2.Position = 0
sr2.Read(biteArray, 0, CInt(sr2.Length))
'm_pdfExporter.Export(Path.GetTempPath & "\" & "12214" & ".pdf")
Response.Clear()
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/pdf"
'Response.BinaryWrite(biteArray)
Response.AddHeader("Content-Disposition", "attachment;filename=" & "12214" & ".pdf")
Response.BinaryWrite(System.IO.File.ReadAllBytes(Server.MapPath("~") & "12214" & ".pdf"))
Catch ex As Exception
End Try
End Sub
Try using c1PrintDocument1.Export("filename.pdf", true) instead.
Thanks,
Richa

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If