Keeping only certain parts of a multiline text box - vb.net

net 2.0 program and in it I have a multi line text box.
For one of my operations I only need to retrieve certain parts of the txt box
for instance
I need to retrieve the following
01-11-2013 15-18-12 -
Computer: 740TMP
01-11-2013 15-18-13 -
Computer: 740TMP
The text box can have just 1 entry or 30 entry. I know I can truncate the lines but then I would still have extra lines in the final results.. Any Ideas?

Use a List(Of String) to store the result with your desired lines. Then use a loop to iterate all lines in the TextBox and take what you need.
For example:
Dim desiredLines As New List(Of String)()
Dim allLInes As String() = textBox1.Lines
Dim datePattern As String = "dd-MM-yyyy HH-mm-ss"
For i As Integer = 0 To allLInes.Length - 1
Dim line As String = allLInes(i).Trim()
Dim dt As Date
If line.Length >= datePattern.Length AndAlso _
Date.TryParseExact(line.Substring(0, datePattern.Length), datePattern, Nothing, Globalization.DateTimeStyles.None, dt) Then
desiredLines.Add(dt.ToString(datePattern))
ElseIf line.StartsWith("Computer:") Then
desiredLines.Add(line.Split("-"c)(0).TrimEnd())
End If
Next

Related

Correct way to split csv file to remove extra " VB.net

I am importing a csv file into a datatable in a vb.net form application. When I import the csv file my code is adding an extra set of " around my dates. This is causing an error where my input array has more values than columns on my datatable. How do I remove the extra " with the split statement or another way.
Original line from csv file
10411392601,Josue Smolcic 32278,10411392601,ProJet 7000,Not Burned-In,0.0,,0,, ,10411392601 was started on 2019-10-02 11:41:13.
This Machine is Pending and still requires a passing inspection in Assembly / Integration. See Inspection Record #12367.,1.0,,This Machine is Pending and still requires a passing inspection in Assembly / Integration.
,"Oct 02, 2019","Oct 02, 2019 11:42 AM","Oct 02, 2019 11:41 AM",Pending, (2019-10-02 11:42:11)
After my code runs when I add a watch to the finalline variable I get this.
"10411392601,Josue Smolcic 32278,10411392601,ProJet 7000,Not Burned-
In,0.0,,0,, ,10411392601 was started on 2019-10-02 11:41:13. This Machine is Pending and still requires a passing inspection in Assembly / Integration. See Inspection Record #12367.,1.0,,This Machine is Pending and still requires a passing inspection in Assembly / Integration.
,""Oct 02, 2019"",""Oct 02, 2019 11:42 AM"",""Oct 02, 2019 11:41 AM"",Pending, (2019-10-02 11:42:11)"
Looking at the bottom line of both the examples you can see around the Oct dates there is an extra set of parentheses. How do I remove these?
Here is my vb code.
Private Sub MergetblAllMachines()
Dim path As String = "Pathway.csv"
Dim f As Integer = 0
Dim myreader As New StreamReader(path)
Dim fullfilestr As String = myreader.ReadToEnd
myreader.Close()
myreader.Dispose()
Dim lines As String() = fullfilestr.Split(ControlChars.Lf)
Dim recs As New DataTable()
Dim sarr As String() = lines(0).Split(","c)
For Each s As String In sarr
f = f + 1
recs.Columns.Add(New DataColumn())
' MsgBox(s)
Next
Dim row As DataRow
Dim finalline As String = " "
For Each line As String In lines
row = recs.NewRow()
finalline = line.Replace(Convert.ToString(ControlChars.Cr), "")
row.ItemArray = finalline.Split(","c)
recs.Rows.Add(row) '-----Here is where my code bugs out------
Next
end sub
-
-
-
-----------------------Updated (Correct code)-----------------
attempting to use the textfieldparser class I have removed the double quotes but now I am having a hard time getting the strings split correctly. Here is my updated code.
Dim path As String = "path.csv"
Dim f As Integer = 0
Dim myreader As New StreamReader(path)
Dim fullfilestr As String = myreader.ReadToEnd
myreader.Close()
myreader.Dispose()
Dim lines As String() = fullfilestr.Split(ControlChars.Lf)
Dim recs As New DataTable()
Dim sarr As String() = lines(0).Split(","c)
For Each s As String In sarr
f = f + 1
recs.Columns.Add(New DataColumn())
' MsgBox(s)
Next
Dim SplitRow As String = Nothing
Using myreader1 As New Microsoft.VisualBasic.FileIO.TextFieldParser("path.csv")
myreader1.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
myreader1.Delimiters = New String() {","}
Dim currentrow As String()
While Not myreader1.EndOfData
Try
currentrow = myreader1.ReadFields()
recs.Rows.Add(currentrow)
Catch ex As Exception
End Try
End While
End Using
After running this all of each row is in the first cell of each row in the datatable. I need to split on the commas and then fill in the rest of each row. A side note, Recs is the datatable i am attempting to put everything into.

How to format textfiles values retrieved from a directory and displayed in datagridview in vb.net

The problem now is how would I be able to format the values being displayed in datagridview from textfiles.
I have retrieved values from looping through textfiles removed the first two strings. Now I want to add separators or change the format of the displayed value like, for example:
textfile lines: result:
01Sample - line1
022 - line2
0306212019 - line3 06/21/2019
041234567890 - line4 12,345,678.90
I have already tried this one changing the defaultcellstyle but since the values are from textfiles in a directory its not affecting the output
DataGridView1.Columns("Gross Sales").DefaultCellStyle.Format = "##,0"
Private Sub ReadTextFiles()
Dim dt As New DataTable
dt.Columns.Add("Date")
dt.Columns.Add("Gross Sales")
Dim Folder As New IO.DirectoryInfo("c:\test\")
Dim lstLines As New List(Of String)
For Each fileentries As String In Folder.GetFiles("s*", IO.SearchOption.AllDirectories).OrderByDescending(Function(x) x.Name).Select(Function(x) x.FullName)
lstLines.AddRange(File.ReadAllLines(fileentries))
Next
Dim i As Integer
Dim OuterLoopIterations As Integer = CInt(lstLines.Count / 22)
For iterations = 0 To OuterLoopIterations - 1
Dim row = dt.NewRow
For col = 0 To 21
row(col) = lstLines(i).Remove(0, 2) 'i have removed the first 2 characters of each string
i += 1
Next
dt.Rows.Add(row(2), row(5), row(12), row(13), row(14), row(15), row(7), row(8), row(11))
Next
DataGridView1.DataSource = dt
'the code i tried applying
DataGridView1.Columns("Gross Sales").DefaultCellStyle.Format = "##,0"
this is my expected result
Current datagrid view:
the result should be for date column: 06/07/2019
for the gross : 48,990.14
Edit:
I tried this one
Dim B As Double
Dim Folder As New IO.DirectoryInfo("c:\test\")
Dim lstLines As New List(Of String)
For Each fileentries As String In Folder.GetFiles("s*", IO.SearchOption.AllDirectories).OrderByDescending(Function(x) x.Name).Select(Function(x) x.FullName)
B = CDbl(Val(fileentries))
lstLines.AddRange(File.ReadAllLines(B))
Next
If you want to format something as a number then it has to be a number. That means that, for example, if you read the text "1234.5" from the file and you want to display it as 1,234.50 in your grid then you have to convert the String you read to a Double or Decimal. If you do that then the numeric format specifier you're using in the grid column will work.

replace a line in richtextbox vb.net

I have this code but it have errors , what should i do ?
Dim lines As New List(Of String)
lines = RichTextBox1.Lines.ToList
'Dim FilterText = "#"
For i As Integer = lines.Count - 1 To 0 Step -1
'If (lines(i).Contains(FilterText)) Then
RichTextBox1.Lines(i) = RichTextBox1.Lines(i).Replace("#", "#sometext")
'End If
Next
RichTextBox1.Lines = lines.ToArray
Update: while the following "works" it does only modify the array which was returned from the Lines-property. If you change that array you don't change the text of the TextBox. So you need to re-assign the whole array to the Lines-property if you want to change the text(as shown below). So i keep the first part of my answer only because it fixes the syntax not the real issue.
It's not
RichTextBox1.Lines(i).Replace = "#sometext"
but
RichTextBox1.Lines(i) = "#sometext"
You can loop the Lines forward, the reverse loop is not needed here.
Maybe you want to replace all "#" with "#sometext" instead:
RichTextBox1.Lines(i) = RichTextBox1.Lines(i).Replace("#","#sometext")
So here the full code necessary (since it still seems to be a problem):
Dim newLines As New List(Of String)
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
newLines.Add(RichTextBox1.Lines(i).Replace("#", "#sometext"))
Next
RichTextBox1.Lines = newLines.ToArray()
But maybe you could even use:
RichTextBox1.Text = RichTextBox1.Text.Replace("#","#sometext")`
because if we have # abcd this code change it to # sometextabcd ! I
Want a code to replace for example line 1 completely to # sometext
Please provide all relevant informations in the first place next time:
Dim newLines As New List(Of String)
For Each line As String In RichTextBox1.Lines
Dim newLine = If(line.Contains("#"), "#sometext", line)
newLines.Add(newLine)
Next
RichTextBox1.Lines = newLines.ToArray()

How to create a csv file from a formatted text file

I have a text file with hundreds of prospects that I'm trying to convert to csv for importing.
Format for whole document.
Prospect Name
Description
Website
Prospect Name
Description
Website
How would I write a vb program to loop through this to make a csv file. Every 4 lines is a new prospect.
Get your file contents as an IEnumerable(of String), and spin through it, adding a CSV row for every record (into a new list(of String)). Finally write the file contents. You'll probably want to add a header row.
Dim lstLines As IEnumerable(Of String) = IO.File.ReadLines("C:\test\ConvertToCSV.txt")
Dim lstNewLines As New List(Of String)
Dim intRecordTracker As Integer = 0
Dim strCSVRow As String = String.Empty
For Each strLine As String In lstLines
If intRecordTracker = 4 Then
intRecordTracker = 0
'Trim off extra comma.
lstNewLines.Add(strCSVRow.Substring(0, (strCSVRow.Length - 1)))
strCSVRow = String.Empty
End If
strCSVRow += strLine & ","
intRecordTracker += 1
Next
'Add the last record.
lstNewLines.Add(strCSVRow.Substring(0, (strCSVRow.Length - 1)))
'Finally write the CSV file.
IO.File.WriteAllLines("C:\Test\ConvertedCSV.csv", lstNewLines)
Dim count As Integer = -1, lstOutput As New List(Of String)
lstOutput.AddRange(From b In File.ReadAllLines("C:\temp\intput.txt").ToList.GroupBy(Function(x) (Math.Max(Threading.Interlocked.Increment(count), count - 1) \ 4)).ToList() Select String.Join(",", b))
File.WriteAllLines("c:\temp\test\output.txt", lstOutput)

reading file into an array

i have a text file with the following data:
Calculated Concentrations
30.55 73.48 298.25 27.39 40.98 11.21 99.22 33.46 73.99 12.18 30.7
50 28.4 34.33 29.55 70.48 43.09 28.54 50.78 9.68 62.03 63.18 28.4
100 23.83 68.65 10.93 ?????? 31.42 8.16 24.97 8.3 114.97 34.92 15.53
200 32.15 29.98 23.69 ?????? 23.41 33.6 92.03 32.73 13.58 58.44 94.61
400 159.98 18.05 50.94 37.12 15.25 46.75 315.22 69.98 13.58 ?????? 58.77
208.82 11.07 38.15 86.31 35.5 41.88 28.25 5.39 40.83 29.98 54.42 69.48
36.09 13.16 23.26 19.31 147.56 31.86 6.77 19.45 33.6 32.87 205.47 134.21
?????? 17.35 9.96 58.61 13.44 23.97 22.13 145.17 29.55 26.54 37.12 198.33
and i would like to load this data into an array.
how do i enable the user to open a file of his choosing in vb.net?
how do i read these values into an array in vb.net?
i would like to clarify that what person-b has suggested works very very well. specifically the fields = calculationText.split(" ") was exactly what i needed; however, my next issue is the following. the data above is actually in this format:
http://pastebin.com/d29ae565b
where the i need the first value to be 0, then 50, then 100 etc. and i need it to read columns from left to right. the problem is that the values are not reading into the array in this manner. the values are actually reading like this: 6.65, 84.22, ????, 35.15. please help!
To read a file into a String variable, in VB.NET, you can use the System.IO.File.ReadAllText() function. An example is:
Imports System.IO '// placed at the top of the file'
'// some code'
Dim calculationText As String
calculationText = File.ReadAllText("calculations.txt") '// gets all the text in the file'
Where "calculations.txt" is the file name.
To your next point - to allow the user to load a file of their choosing, you can use the OpenFileDialog type. An example:
Dim fileName As String
Dim openDlg As OpenFileDialog
openDlg = New OpenFileDialog() '// make a new dialog'
If openDlg.ShowDialog() = DialogResult.OK Then
'// the user clicked OK'
fileName = openDlg.FileName '// openDlg.FileName is where it keeps the selected name'
End If
Combining this, we get:
Imports System.IO
'// other code in the file'
Dim fileName As String
Dim openDlg As OpenFileDialog
openDlg = New OpenFileDialog() '// make a new dialog'
If openDlg.ShowDialog() = DialogResult.OK Then
'// the user clicked OK'
fileName = openDlg.FileName
End If
Dim calculationText As String
calculationText = File.ReadAllText(fileName)
Now, we need to process the input. First, we need to make a list of decimal numbers. Next, we put everything in the file that is a number in the list:
Dim numbers As List(Of Decimal)
numbers = New List(Of Decimal)() '// make a new list'
Dim fields() As String
fields = calculationText.Split(" ") '// split all the text by a space.'
For Each field As String in fields '// whats inside here gets run for every thing in fields'
Dim thisNumber As Decimal
If Decimal.TryParse(field, thisNumber) Then '// if it is a number'
numbers.Add(thisNumber) '// then put it into the list'
End If
Next
This won't include Calculated Concentrations or ????? in the list. For usable code, just combine the second and last code samples.
EDIT: In response to the comment below.
With List objects, you can index them like this:
Dim myNumber As Decimal
myNumber = numbers(1)
You do not need to use the Item property. Also, when showing it in a message box, you need to turn it into a String type first, like this:
MsgBox(myNumber.ToString())
Once you have the file coming from an OpenFileDialog control or other UI control. Here's something you could do:
Dim filePath As String = "file.txt" ''* file coming from control
Dim fileContents As String = System.IO.File.ReadAllText(filePath)
Dim contentArray() As String = fileContents.Split(" ")
Then you can iterate through the array and TryParse to a number as needed.
OpenFileDialog
Read through character by character, looking for spaces to mark the end of a number, then parse the number an add it to a List. Or if the file is always short, you could use StreamReader.ReadToEnd and String.Split.
Code to start with (auto-converted from C#):
Dim ofd = New OpenFileDialog()
ofd.Title = "Select Data File"
If ofd.ShowDialog() = DialogResult.OK Then
Dim data As New StreamReader(ofd.FileName.ToString())
While data.Read() <> " "c
End While
' Read past Calculated
While data.Read() <> " "c
End While
' Read past Concentrations
Dim concentBuilder As New StringBuilder()
Dim last As Integer
Dim concentrations As New List(Of Double)()
Do
last = data.Read()
If last = " "c OrElse last = -1 Then
Dim concentStr As String = concentBuilder.ToString()
concentBuilder.Remove(0, concentBuilder.Length)
Dim lastConcentration As Double
Dim parseSuccess As Boolean = [Double].TryParse(concentStr, lastConcentration)
If Not parseSuccess Then
Console.[Error].WriteLine("Failed to parse: {0}", concentStr)
Else
concentrations.Add(lastConcentration)
End If
Else
concentBuilder.Append(CChar(last))
End If
Loop While last <> -1
For Each d As Double In concentrations
Console.WriteLine(d)
Next
End If