Error with VB ParseFileText method - vb.net

When I run this I made a dummy "Button1" to test populate the fields they will successfully fill out the texts boxes. How ever I will have it parse that file every minute, and when I do it again I get the error shown below. By adding the routine "DisplayForm_Load" to the button1_click even it would work fine.
My question is I'm pretty sure I shouldn't have to redefine this every time? I think I'm not setting the index back to 0 or something along those lines. From what I've been able to understand from MS website is its like its indexing things in the array that don't exist.
Error received:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication4.exe
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private Directory As String ' Used to hold the folder directory to push/pull data from.
Private FileParser As Microsoft.VisualBasic.FileIO.TextFieldParser
Private Sub PushButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles PushButton.Click
' Sends information to txt file.
' This bit works fine, just writes code to txt file that can be parsed below.
End Sub
Sub DefineTextFieldParse_Load() Handles MyBase.Load
' Instantiate teh TextFieldParser and the set the delimiter
Dim FileName As String = "C:\Users\Caleb\Documents\TestDoc.txt"
Try
FileParser = New FileIO.TextFieldParser(FileName) '' Selects File to Parse
FileParser.TextFieldType = FieldType.Delimited
FileParser.SetDelimiters(",")
Catch ex As Exception
' Errors
MessageBox.Show("Unable to read the file" & "," & FileName)
End Try
End Sub
Sub UpdateCheck()
' Checks share txt file for update.
Dim FileName As String = "C:\Users\<Me>\Documents\TestDoc.txt"
Dim FieldString() As String
'Read the file
If Not FileParser.EndOfData Then
FieldString = FileParser.ReadFields()
' 1st Field
NIS1TextBox.Text = FieldString(0)
' 2nd Field
NIS2TextBox.Text = FieldString(1)
' You get the idea...All Testboxes identified above in the write section
' Repeats 12 more times...
EODTextBox.Text = FieldString(14)
InfoRichTextBox.Text = FieldString.LastOrDefault()
End If
End Sub
Sub PushUpdate()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
'DefineTextFieldParse_Load()_Load() ' When Enabled code works fine when commented out generates alert.
UpdateCheck()
End Sub
End Class

mchihinney - I did review https://msdn.microsoft.com/en-us/library/hks5e2k6.aspx
However what I found was the issue was with the formatting of the text file. The problem I found was with the text file there was a second line which was blank, so when it tried to parse nothing it through the error. Deleting the second line from the .txt file and worked as expected.

Related

Debug logging VB.net

I'm trying to create a Debug log for my application, and I'd like to document everything to the log.
%TimeStamp% - Loaded main form
%TimeStamp% - Loaded Settings
%TimeStamp% - Entered Ready state
etc.
I've got a function that creates a folder to house the debug log, and creates the debug file accordingly:
Dim DebugFile As String = String.Format(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\App\Debug_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Public Sub Debug_File_Check()
' Set a variable to the My Documents path.
If (Not System.IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\App\")) Then
System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\App\")
End If
End Sub
And a function that opens the debug file and writes a line to it:
Public Sub Debug()
Using writer As New StreamWriter(DebugFile, True)
If File.Exists(DebugFile) Then
writer.WriteLine(%DEBUG MESSAEGE + " Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End If
End Using
End Sub
My question is, how can I pass information from something like:
Private Sub FrmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Debug_File_Check()
Debug("The form has loaded")
End Sub
Where it, on one line, will write the debug line to my debug.txt file?
I've never dealt with debug logging before, so not even sure if I'm on the write track.

Autocomplete dictionary from a RichTextBox

While this code works fine in my RichTextBox, how do you do it from a dictionary in VB?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'AutoComplete.Add("do")
AutoComplete.Add("double")
AutoComplete.Add("Apple")
AutoComplete.Add("Car")
AutoComplete.Add("Table")
AutoComplete.Add("Plate")
How do you do this from a dictionary in VB?
So this isn't an actual .NET dictionary? Ambiguous title!
Assuming each line is a separate word to populate your 'dictionary':
Public Sub PopulateDict()
For Each word As String In File.ReadAllLines("path")
AutoComplete.Add(word)
Next
End Sub
Something like this, yes?
Simple, you just need to read in the dictionary text file, parse the words from it, and then add them to your ArrayList.
Here's an example:
Private AutoComplete As New ArrayList
Private Sub AddDictionary()
Try
' Create an instance of StreamReader to read from a file.
Using sr As StreamReader = New StreamReader("dictionary.txt")
Dim line As String
Dim pieces As String()
' Read every line in the file
' Split the line by the delimiter
' Add the individual pieces to the AutoComplete ArrayList
Do
line = sr.ReadLine()
pieces = line.Split(" ")
For Each piece In pieces
AutoComplete.Add(piece)
Next
Loop Until line Is Nothing
' Close the dictionary file StreamReader
sr.Close()
End Using
Catch E As Exception
' Let the user know what went wrong.
MsgBox("The dictionary file could not be read:\n" & E.message, _
MsgBoxStyle.Critical, _
"Error loading file!")
End Try
End Sub
Note: I don't know how your dictionary file is formatted, so in my example code I'm just splitting the lines into individual words using spaces.
You could call the AddDictionary() sub from your Form1_Load() method to add the words to the AutoComplete dictionary at startup.

VB.net program hangs when asked to read .txt

I am attempting to read a .txt file that I successfully wrote with a separate program, but I keep getting the program stalling (aka no input/output at all, like it had an infinite loop or something). I get the message "A", but no others.
I've seen a lot of threads on sites like this one that list all sorts of creative ways to read from a file, but every guide I have found wants me to change the code between Msgbox A and Msgbox D. None of them change the result, so I'm beginning to think that the issue is actually with how I'm pointing out the file's location. There was one code (had something to do with Dim objReader As New System.IO.TextReader(FileLoc)), but when I asked for a read of the file I got the file's address instead. That's why I suspect I'm pointing to the .txt wrong. There is one issue...
I have absolutely no idea how to do this, if what I've done is wrong.
I've attached at the end the snippet of code (with every single line of extraneous data ripped out of it).
If it matters, the location of the actual program is in the "G01-Cartography" folder.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine()
MsgBox("C")
End Using
MsgBox("D")
End Sub
What does running this show you in the debugger? Can you open the Map_Cygnus.txt file in Notepad? Set a breakpoint on the first line and run the program to see what is going on.
Private BaseDirectory As String = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\"
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim WholeMap = File.ReadAllText(Path.Combine(BaseDirectory, "Map_Cygnus.txt"))
Debug.Print("Size Of Map: {0}", WholeMap.Length)
End Sub
It looks like you're using the correct methods/objects according to MSDN.
Your code runs for me in an new VB console app(.net 4.5)
A different approach then MSGBOXs would be to use Debug.WriteLine or Console.WriteLine.
If MSGBOX A shows but not B, then the problem is in constructing the stream reader.
Probably you are watching the application for output but the debugger(visual studio) has stopped the application on that line, with an exception. eg File not found, No Permission, using a http uri...
If MSGBOX C doesn't show then problem is probably that the file has problems being read.
Permissions?
Does it have a Line of Text?
Is the folder 'online'
If MSGBOX D shows, but nothing happens then you are doing nothing with WholeMap
See what is displayed if you rewite MsgBox("C") to Debug.WriteLine("Read " + WholeMap)
I have a few suggestions. Firstly, use Option Strict On, it will help you to avoid headaches down the road.
The code to open the file is correct. In addition to avoiding using MsgBox() to debug and instead setting breakpoints or using Debug.WriteLine(), wrap the subroutine in a Try...Catch exception.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine() 'dimming a variable inside a block like this means the variable only has scope while inside the block
MsgBox("C")
End Using
MsgBox("D")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that you normally should only catch whatever exceptions you expect, but I generally catch everything while debugging things like this.
I would also like to point out that you are only reading one line out of the file into the variable WholeMap. That variable loses scope as soon as the End Using line is hit, thereby losing the line you just read from the file. I'm assuming that you have the code in this way because it seems to be giving you trouble reading from it, but thought I would point it out anyway.
Public Class GameMain
Private WholeMap As String = ""
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
Using File As New StreamReader(FileLoc)
WholeMap = File.ReadLine() 'dimming the variable above will give all of your subs inside class Form1 access to the contents of it (note that I've removed the Dim command here)
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

File not being written to in vb.net

I did some google searching and everyone gives me the same answer which isn't working. I hope its something simple I am missing. I am trying to test write a line to a txt file. The file was created just fine when I used similar code, and no errors are thrown, the txt just doesn't write/save to the file. I am using stream writer in VB.
Here is my code:
Imports System.IO
Public Class Form1
Private Sub btnGen2DArray_Click(sender As Object, e As EventArgs)
Handles btnGen2DArray.Click
Try
'this is the file created and where it is saved:
Dim fileLoc As String = "c:\Users\clint\save.txt"
If File.Exists(fileLoc) Then
Using sw As New StreamWriter(fileLoc)
sw.Write("Test line write")
sw.Close()
End Using
End If
MsgBox("C++ 2D array text file created in: " + fileLoc, MsgBoxStyle.OkOnly, "Successful")
Catch ex As Exception
MsgBox("error: " + e.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Close()
End Sub
End Class
I am using vb 2012 if this helps. Normal windows form application.
You need to close your StreamWriter when you are done. sw.Close
You must call Close to ensure that all data is correctly written out
to the underlying stream.
Better yet, use Using. The following would go inside your if:
Using sw As New StreamWriter(fileLoc)
sw.Write("Test line write")
For rowcount As Double = 1 To rows
For colcount As Double = 1 To cols
'when the file write test works I will finish the rest of the code here
Next
Next
End Using
This will automatically dispose of the StreamWriter for you.

handing the OnCreated event of FileSystemWatcher

I implemented this event of the FileSystemWatcher:
Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
If e.Name.ToUpper() == "MYTEXTFILE.TXT" then
' code '
End If
End Sub
Is there a way to monitor if created files are in a textbox similar to this?
Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
If e.Name.ToUpper.contains(textbox1.text) then
' code '
End Sub
Having more than one file in a multiline textbox and every filename is in a separate line requires that you should split the filenames individually and then check each one with the file just created.
Private Shared Sub OnCreated(source As Object, e As FileSystemEventArgs)
' Get an array of the files at each line and remove eventually spurious empty lines
Dim files() = textbox1.Text.Split(New String() {Environment.NewLine}, _
StringSplitOptions.RemoveEmptyEntries)
Dim newFile = e.Name.ToUpper()
for each file in files
if file.ToUpper() = newFile Then
' code '
Exit For
End If
Next
End Sub
I'm not 100% clear I understand your question, but I'm assuming that you want to compare the name of the file that was just created with the name of a file in a textbox.
1) Is the text in the textbox also uppercase? I see you uppercase the name of the file before comparing.
2) Is the text in the textbox "containable" in the name of the file, maybe the other way around?
3) Should the condition be .Equal instead of .Contains?