"Object reference not set to an instance of an object" message - vb.net

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!

Related

Reading a particular line of a text file in an array in 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.)

Using an array to search a file VB

I have a program that needs to look through a text file line by line, the lines look like this:
10-19-2015 Brett Reinhard All Bike Yoga Run the Studio Design Your Own Strength
These are separated by tabs in the text file.
What I want to do is look at the second value, in this case "Brett Reinhard" and move the full line to another textfile called "Brett Reinhard"
I was thinking of using an array to check to see if the second 'column' in the line matched any value within a given array, if it does I want to perform a specific action.
The way I am thinking of doing this is with a For/next statement, now while it will work it will be a laborious process for the computer that I will be using it on.
The code I am thinking of using looks like this:
For intCounter=0 to Whatever Number is the last number of the array
If currentfield.contains(array(intCounter)) Then
Open StreamWriter(File directory & array(intcounter) & ".txt")
Streamwriter.Writeline(currentfield)
End IF
Is there a better way of doing this, such as referencing the second 'column' in the line, similar to the syntax used in VBA for excel.
Name=Cells(1,2).Value
If you can guarantee that a line will only use the tab characters as field separators, you can do something along this:
Open the stream for reading text
Open a stream for writing text
Read a line of text
Use the Split method to break the incoming line into an array of fields
If the second element in the array is your sentinel value, write the original line to the writer
Repeat yourself until you have reached the end of file (ReadLine will return Nothing, or null for those c# folk).
Close and dispose of your stream objects.
If you aren't sure of the format, you will want to take the hit and use the TextFieldParser as mentioned in an earlier comment.
So while its not using an array to search a file, what I ended up doing works just as well. I ended up using the split method thanks to #Martin Soles.
Here is what I came up with:
Sub Main()
Dim intCount As Integer = 1
Dim words As String
Dim split As String()
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
"I:\Games, Events, & Promotions\FRP\Back End\Approved.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
words = currentField
split = words.Split(New [Char]() {CChar(vbTab)})
For Each s As String In split
If intCount = 2 Then
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("I:\Games, Events, & Promotions\FRP\Back End\" & s & ".txt", True)
file.WriteLine(currentField)
file.Close()
End If
intCount = intCount + 1
Next s
intCount = 1
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
End Sub 'Main
Thank you guys for the suggestions.
For right now the split method will work for what is needed.

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()

Call Function when User Types Certain Keyword

Okay, so I am working on a small scripting language using a VB Console Application.
I want the user to input "say('something')" and it calls the function I made named "say", is there a way to call the function and still use the following code:
Module Module1
Sub say(sayline)
Console.WriteLine(sayline)
End Sub
Sub Main()
Dim cmd As String
Console.WriteLine(">")
Do
Console.Write("")
cmd = Console.ReadLine()
If cmd IsNot Nothing Then cmd
Loop While cmd IsNot Nothing
End Sub
End Module
No, you cannot just call a method from user's string. You need to interpret the entered data.
First, you need to split your method name and arguments so that entered "say('something')" will transform to say and something. Remember that user can enter wrong data and you need to check if this call is correct - it's all about syntactic and lexical analysis. I hope you understand how to do this because it is pretty difficult.
Then, you need to check if you have a method called say. In case of plain and simple structure, switch construction will be enough. If your have such method, then pass something argument to this method. Else, output something like "unknown method".
If you wanted to call the method say upon typing the word say(something) and display the word something, then you can just have a certain condition that if the user types the word say within the input then call say method else, do whatever you want to do under else portion. Parse the input and omit the word say from the input and display it then.
You can have your code this way for example. (I just copied your code and added some codes to meet what you wanted... in my understanding)
Module Module1
Sub say(ByVal sayline)
Console.WriteLine(sayline)
End Sub
Sub Main()
Dim cmd As String
Do
Console.Write("> ")
cmd = Console.ReadLine()
Try
If cmd IsNot Nothing And cmd.Substring(0, 3).ToUpper().Equals("SAY") Then
say(parseInput(cmd))
End If
Catch ex As Exception
Console.WriteLine("message here")
End Try
Loop While cmd IsNot Nothing
End Sub
Function parseInput(ByVal cmd As String) As String
Dim input As String = ""
For index As Integer = 3 To cmd.Length - 1
If Char.IsLetter(cmd) Then
input += cmd.Substring(index, 1)
Else
input = input
End If
Next
Return input
End Function
End Module

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.