partial .txt file to datagridview vb.net - vb.net

i have a user interface form that let's you upload a text file to a datagridview as follows
Sub Datagrid()
Dim sw = System.Diagnostics.Stopwatch.StartNew()
Using stream As System.IO.FileStream = System.IO.File.OpenRead(TextBox1.Text)
Using reader As New System.IO.StreamReader(stream)
Dim line As String = reader.ReadLine()
While (line IsNot Nothing)
Dim columns = line.Split(";")
line = reader.ReadLine()
Dim index = Me.DataGridView1.Rows.Add()
Me.DataGridView1.Rows(index).SetValues(columns)
End While
End Using
End Using
sw.Stop()
End Sub
Well, now my problem is that i don't want to put the full txt file in that datagridview, just from line N.
Is it possible to do that? Like creating a querytabel and selecting a fixed value?
p.e., in line 5 there's always the text "Values:" . Can i select all the lines after that to put in the datagridview? i googled everywhere but found nothing. and there's no "sample" code to give me a start . thank you all !

Dim n As Integer = 5
Dim lines As IEnumerable(Of String) = IO.File.ReadAllLines("textbox1.text").Skip(n)
'Gets every line after a certain line count
'Create a new datatable and add some columns
Dim dt As New DataTable
dt.Columns.AddRange((From columnIndex As Integer In Enumerable.Range(1, lines.First.Split(";"c).Count) Select New DataColumn("Column" & columnIndex.ToString())).ToArray())
'Add each line as a row to the datatable
For Each line As String In lines
dt.Rows.Add(line.Split(";"c))
Next
'Set the datasource of the datagridview
MyDataGridView.DataSource = dt

Related

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 edit a file based on criteria and save it

I have a file that has dates and results of tests, written line by line. I would like to edit the file such that any line that does not have today's date is deleted and then the file is saved (with the unwanted lines deleted). Help will be greatly appreciated.
Dim rawlines() As String
Dim outputlines As New List(Of String)
rawlines = File.ReadAllLines("C:\users\user10\rslts.csv")
For Each line As String In rawlines
If line.Contains(today()) = True Then
outputlines.Add(line)
End If
Next
Read Lines:
Dim rawlines() As String
Dim outputlines As New List(Of String)
rawlines = File.ReadAllLines("C:\users\user10\rslts.csv")
For Each line As String In rawlines
If line.Contains(today()) = True Then
outputlines.Add(line)
End If
Next
Write lines to new file:
Dim MyFile As StreamWriter
File.Create("c:\test\TheResults.csv").Close()
MyFile = File.AppendText("c:\test\TheResults.csv")
For Each Line As String In outputlines
MyFile.WriteLine(Line)
Next
MyFile.Close()

Read textfile, specific line. VB.net

I've got a text file like this:
EntityList = 0x04A4BA64
LocalPlayer = 0x00A30504
FlashDuration = 0x0000A2F8
RadarBase = 0x04E807BC
ScoreBoardBase/GameResources = 0x04A6BCBC
ServerBase = 0x04E92A10
EnginePointer = 0x005B6314
SetViewAngles = 0x00004D0C
CrosshairIndex = 0x0000AA44
GlowObjectBase = 0x00000000
ViewMatrix1 = 0x04A3D604
ViewMatrix2 = 0x04A3D714
And I'd like to read the textfile from my vb.net program and, for example, on the first line where it says EntityList = 0x04A4BA64, I would love to get the 0x04A4BA64 from it and save it as a Integer.
I tried to do something like this, but this isn't what I really want and it's not working either.
Public Sub Test()
Dim reader As New System.IO.StreamReader("C:\test.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
End Sub
Public oEntityList As Integer = ReadLine(1, allLines)
You need to open the file and select only the lines that contains your pattern then convert the second part of the line to an integer given a base 16
Dim values = new List(Of Integer)()
For Each line in File.ReadLines("C:\test.txt") _
.Where(Function(x) x.Trim().StartsWith("EntityList"))
Dim parts = line.Split("="c)
if parts.Length > 1 Then
values.Add(Convert.ToInt32(parts(1).Trim(), 16)
End If
Next

skip first row when reading excel CSV file

I found how to do this in several languages but not in .net (specifically vb.net). I am using OLeDbCommand to read both CSV and Excel files. In case of Excel I can skip first row and select second row onwards by specifying a range of cells. But in case of CSV, I am not sure how to do it.
Current code looks like:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [" + Path.GetFileName(FileName) + "]", cn)
Here we give the file, not the sheet. So I am bit stuck.
From my experience reading a text file like this is very restrictive. It only allows you to read the whole file, because you can't specify a table name. You might be better of reading each line and making table rows and adding them to a table. If the first row is headers you can use that to make the columns, otherwise hard code the columns.
Here's a simple little method that fills a datatable with the data from a .csv file, that you should be able to use:
Private Sub GetData(ByRef dt As DataTable, FilePath As String, Optional ByVal Header As Boolean = True)
Dim Fields() As String
Dim Start As Integer = CInt(Header) * -1
If Not File.Exists(FilePath) Then
Return
End If
dt.Clear()
Dim Lines() As String = File.ReadAllLines(FilePath)
If CBool(Start) AndAlso dt.Columns.Count = 0 Then
Lines(0) = Lines(0).Replace(Chr(34), "")
For Each h As String In Lines(0).Split(",")
dt.Columns.Add(h)
Next
End If
For I = Start To Lines.Count - 1
Fields = Lines(I).Split(",")
dt.Rows.Add(Fields)
Next
End Sub

Splitting a CSV Visual basic

I have a string like
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
in a file
in two separate lines. I am reading it from the textbox. I have to output ab563372363_C/R and ab563372356_C/R in a text box. I am trying to use the split function for that but its not working..
Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results) 'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)
for the above code, it just prints the whole thing.. What's wrong?
Try this
Private Function GetRequiredText() As List(Of String)
Dim requiredStringList As New List(Of String)
Dim file = "test.txt"
If FileIO.FileSystem.FileExists(file) Then
Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
Dim line As String = reader.ReadLine()
While line IsNot Nothing
requiredStringList.Add(line.Split(",")(1))
line = reader.ReadLine()
End While
reader.Close()
reader.Dispose()
End If
Return requiredStringList
End Function
This will read the file line by line and add the item you require to a list of strings which will be returned by the function.
Returning a List(Of String) may be overkill, but it's quite simple to illustrate and to work with.
You can then iterate through the list and do what you need with the contents of the list.
Comments welcome!!
Also this might work...
Dim query = From lines In System.IO.File.ReadAllLines(file) _
Select lines.Split(",")(1)
this will return an IEnumerable(Of String)
Enjoy
First
Since you are reading the whole text, your FileText would be ending like this:
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
So when you are referencing to your splitStringwith those indexes (1, 13) your result might probably be wrong.
Second
Try to specify what kind of type your array is, Dim splitString as Array should be Dim splitString As String()
Third
Make your code more readable/maintainable and easy to edit (not only for you, but others)
The Code
Private const FirstIndex = 1
Private const SecondIndex = 12
Sub Main
Dim myDelimiter As Char
Dim myString As String
Dim mySplit As String()
Dim myResult1 As String
Dim myResult2 As String
myDelimiter = ","
myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"
mySplit = myString.Split(myDelimiter)
myResult1 = mySplit(FirstIndex)
myResult2 = mySplit(SecondIndex)
Console.WriteLine(myResult1)
Console.WriteLine(myResult2)
End Sub