Reading a particular line of a text file in an array in VB.NET - vb.net

I am trying to read specific lines from a text file in an array (e.g. line 16,25,34, and so on). Could you please let me know if it is possible and how that could be done?
Thanks in advance,
Pouya

Yes it is possible. Since this is not a code based will elaborate how to achieve that. This will depends on the size of your target file. If the size in not to large for your PC's memory then you can read the whole textfile while reading keep the count.
Then start when the file has been read to end to go through your lines using regex.
Check:
VB.NET Read Certain text in a text file
your solution is here:
http://www.dreamincode.net/forums/topic/56497-go-to-a-particular-line-in-a-text-file-using-vbnet/
How to read a specific line from a text file in VB
Ok, here's I've also quoted the code to help you from the second last like I provided above. I'm sure you know how to get data from an Array so instead of line you will add your array.
Public Function
ReadSpecifiedLine(ByVal line As
Integer) As String
'create a variable to
hold the contents of the file
Dim contents As String = String.Empty
'create a variable to
hold our line contents
Dim lineText As String =
String.Empty
' always use a
try...catch to deal
' with any exceptions
that may occur
Try
'Using lineByLine As New IO.StreamReader(_fileName)
Dim lineCount As Integer = 0
While Not lineByLine.EndOfStream
lineByLine.ReadLine ()
If lineCount = line Then
' you can replace the line variable above or use the And Or to match the lines from your array.
lineText = lineByLine.ReadLine()
End If
lineCount += 1
End While
End Using
Catch ex As FileNotFoundException
lineText = String.Empty
_returnMessage = ex.Message
Catch ex As Exception
' deal with any errors
_returnMessage = ex.Message
End Try
Return lineText
End Function
Hope this helps you.(Sorry having some problems in code formatting it some part maybe not formeted, or visible. If End Function is not visible please refer to the link. I've tried so many times to formet this but it not properly formeted, I'm using a Mobile phone.)

Related

Deleting all lines in text file until you get to a word vb.net

Very new to vb.net, apologies if this is basic. I am trying to open up a text file and delete all the lines starting at index 0 until I hit the line that has the word I am looking for. Right now, it just deletes the word I put in it.
' Read the file line by line
Using reader As New IO.StreamReader(fileName)
While Not reader.EndOfStream()
Dim input As String = reader.ReadLine()
'Delete all lines up to String
Dim i As Integer
i = 0
For i = 0 To input.Contains("{MyWord}")
builder.AppendLine(input)
Next
End While
End Using
Partial. You didn't say what to do with the rest of the lines...
Did you mean lines?
Dim ShouldRead as Boolean
Dim builder As New System.Text.StringBuilder
Using reader As New IO.StreamReader(fileName)
'Delete all lines without String
While Not reader.EndOfStream()
Dim input As String = reader.ReadLine()
If input.Contains("{MyWord}") Then ShouldRead = True
If ShouldRead Then
builder.AppendLine(input)
End If
End While
End Using
I would tend to do it like this:
Dim lines = File.ReadLines(filePath).
SkipWhile(Function(line) Not line.Contains(word)).
ToArray()
File.WriteAllLines(filePath, lines)
The File.ReadLines method reads the lines of the file one by one and exposes them for processing as they are read. That's in contrast to the File.ReadAllLines method, which reads all the lines of the file and returns them in an array, at which case you can do as desired with that array.
The SkipWhile method will skip the items in a list while the specified condition is True and expose the rest of the list, so that code will skip lines while they don't contain the specified word and return the rest, which are then pushed into an array and returned. That array is then written back over the original file.
Just note that String.Contains is case-sensitive. If you're using .NET Core 2.1 or later then there is a case-insensitive overload but older versions would require the use of String.IndexOf for case-insensitivity.

Trying to close textfile after line is read

Im trying to output the data from the second line of my textfile to a datagridview but when doing so it is also outputting every line after the the second line. This is what I have tried. Thanks
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
For index = 1 To lines.Length - 1
Dim cells = lines(index).Split(","c)
dgvOutput.Rows.Add(cells)
FileClose()
It's outputting every line after the second line, because that's what you're telling it to do when you iterate through the array of strings returns from ReadAllLines.
IO.File.ReadAllLines does not leave an output stream open. The file is closed. What it does do, is return a zero-based (by default) array of the contents of the file, with line breaks being the delimiter for the split.
To just get the contents of the second line, using ReadAllLines, this is what you need:
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
If lines.length >= 2 Then
Dim cells = lines(1).Split(","c)
dgvOutput.Rows.Add(cells)
End If
Now, that does have the overhead of reading the entire file in. If you open the file using a reader object, then you only need to read the first and second lines of the file to get that second line.
That would be something like this:
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(OrderId & ".txt")
Dim a as String
' This reads the first line, which we throw away
reader.ReadLine()
a = reader.ReadLine()
reader.Close()
Dim cells = a.Split(","c)
dgvOutput.Rows.Add(cells)
You would need to test your explicit circumstances to determine which is better for what you're trying to do.
Your loop is executed over all lines skipping just the first line.
While I cannot see what happen in the FileClose call it seems to not have any sense because ReadAllLines has already closed the file.
You can get the second line of your file with a single line of code
Dim line as String = File.ReadLines(OrderID & ".txt").Skip(1).Take(1).FirstOrDefault()
' this check is required to avoid problems with files containing 0 or 1 line
if line IsNot Nothing Then
Dim cells = line.Split(","c)
dgvOutput.Rows.Add(cells)
End If
Notice that I have replaced the ReadAllLines with ReadLines. This is better because using this method you don't read all lines when you need only the second one (if it exists). More info at ReadLines vs ReadAllLines
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
Dim SecondLine = lines(1)
File.ReadAllLines opens and closes the file for you so there is not need to add code to close it.

Visual Basic Append to a specific point in a text file

I am currently trying to manipulate a line in a file that we are using to retain data, using comma delimiters. For example -
121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA
If I assume that the last line is always a unique code, is it possible to identify that line in the text file and append it with another field?
Prior research has been reading through the APIs for StreamReader and StreamWriter, and looking through other StackOverflow questions, however most questions seem focused on just appending to the end of the file, or in different languages!
As always thank you for your time, and if there is anything I've left off please let me know!
You can't manipulate a line in a file in any reasonably easy way.
There are no methods to work with lines in a file, because files are not line based. They are not even character based. The bytes in the file are decoded into characters, then the line break characters are recognised and the characters can be split into lines.
The easiest way to manipulate a line is to read the entire file into a string array, change the string that you want change, then write the entire string array to the file.
Example:
Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
Dim line As String = lines(i)
If line.StartsWith("12456,") Then
lines(i) = line & ",More data"
End If
Next
File.WriteAllLines(fileName, lines)
If you are looking for a way to parse Each line with StreamReader and StreamWriter: Here it is:
'You will need Imports System.IO
Dim TheNewFile As String
Dim MyLine As String
Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
Dim MyReader As New StreamReader(MyStream2)
Dim MySettings As New StringReader(MyReader.ReadToEnd)
MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
MyReader.Close()
MyStream2.Close()
Try
Do
MyLine = MySettings.ReadLine
'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
If MyLine Is Nothing Then Exit Do
'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
TheNewFile = TheNewFile & MyLine & vbCrLf
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'-----------------Write The new file!!!----------------
Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
Dim MyWriter3 As New StreamWriter(MyStream3)
MyWriter3.Write(TheNewFile & "Test")
MyWriter3.Close()
MyStream3.Close()

StreamReader not finding end of file

I simply need to read lines from a text file and show them. When I run this I can see that id does what I want, but after it reads the last value it just shows a blank form on my screen and does not move on. It seems like it can't find the end of the file or something. I don't get an error.
Using sr As New System.IO.StreamReader(Application.StartupPath & "\myfile.cfg")
Dim Line As String = ""
Dim i As Integer = 0
Dim temp_array As Array
Do While Line IsNot Nothing
Line = sr.ReadLine
temp_array = Line.Split("=")
'MessageBox.Show(temp_array(0))
Loop
End Using
That is bad code because you're actually going to use Line before testing whether it's Nothing. Here are two good options for looping through the lines of a text file:
Using reader As New StreamReader(filePath)
Dim line As String
Do Until reader.EndOfStream
line = reader.ReadLine()
'...
Loop
End Using
For Each line In File.ReadLines(filePath)
'...
Next
As you can see, the second is far more concise but it does require .NET 4.0 or later.

"Object reference not set to an instance of an object" message

I keep getting window that pops up when I run a VB.NET console program I made that simply says "Object reference not set to an instance of an object." The window doesn't even say "error" or anything--the title is simply the name of the project. However...I'm assuming this is something I don't want.
I searched around a bit and found posts about similar messages but couldn't figure out how they applied to my situation.
Here is some of my code. (This program is supposed to take some data from a preformatted text file that describes the geometry of a cross section of a river and systematically enters some new geometric data to represent the riverbed being cleaned/cleared out in a certain way, and then write the new data to a new file in a similar format.)
Imports System
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Module module1
Public Sub Main()
Using sr As New StreamReader("C:\inputfile.txt")
Using outfile As New StreamWriter("C:\outputfile.txt")
Dim line As String = ""
Dim styles As Globalization.NumberStyles
styles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
Dim stations(-1) As Double
Dim elevations(-1) As Double
Dim i As Integer = 0
Do
Try
line = sr.ReadLine()
Dim stringarray() As String = line.Split()
ReDim Preserve stations(i)
ReDim Preserve elevations(i)
stations(i) = Double.Parse(stringarray(0), styles)
elevations(i) = Double.Parse(stringarray(1), styles)
Catch ex As Exception
MsgBox(ex.Message)
End Try
i = i + 1
Loop Until line Is Nothing
Dim min As Double = elevations(0)
(some more code.....)
End Using
End Using
End Sub
End Module
I only included the first part of my code because when I put a break at the "Loop Until line Is Nothing" statement, the message didn't come up until after I went through the break, but when I put the break at the "Dim min As Double = elevations(0)" statement, the message came up before the program got to the break.
I don't really get what's wrong with my code. Anyone have any ideas?
Thanks!
See if this works any better:
Public Sub Main()
Dim styles As Globalization.NumberStyles = Globalization.NumberStyles.AllowLeadingSign Or Globalization.NumberStyles.AllowDecimalPoint
Dim stations As New List(Of Double)
Dim elevations As New List(Of Double)
For Each line As String in File.ReadLines("C:\inputfile.txt")
Try
Dim stringarray() As String = line.Split()
stations.Add(Double.Parse(stringarray(0), styles))
elevations.Add(Double.Parse(stringarray(1), styles))
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next Line
Dim min As Double = elevations(0)
Using outfile As New StreamWriter("C:\outputfile.txt")
End Using
End Sub
Note that I moved your output file to the end... you haven't written anything yet, and so it's a good idea to wait as long as possible to open it, to keep it open for as short a time as possible.
The code fails after the last line has been read because the exit condition (Loop Until) doesn't know that you have reached the end of file. So another loop is started and the code tries to read an inexistent line. The last ReadLine returns Nothing, but the code tries to split it.
You could add a check before trying to split the line and jump directly to the Loop Until statement if you don't have anymore lines to read. Of course I also suggest to remove the array redim at every loop and use a more flexible List(Of Double)
Dim stations = New List(Of Double)
Dim elevations = New List(Of Double)
Do
Try
' After the last line this command returns null (Nothing in VB)
line = sr.ReadLine()
if line IsNot Nothing Then
Dim stringarray() As String = line.Split()
stations.Add(Double.Parse(stringarray(0), styles))
elevations.Add(Double.Parse(stringarray(1), styles))
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Loop Until line Is Nothing
OK...I feel really dumb now...after reading through all of your answers and looking at Steve's code, I realized my code was going through the loop one last time where "line" was set as nothing at the beginning of the loop and it was still trying to add "nothing" as an element to the arrays. The key to fixing it was adding an "If line IsNot Nothing" statement before the statements adding elements to the arrays, which Steve had.
Thank you all for your answers!