Using Try/Catch block to set file path? - visual-studio

I'm having a bit of trouble figuring out an assignment for my Visual Basic course. I am told to assume that a given text file is not in the \bin\Debug folder of my program, so I am trying to throw an exception error and get the correct path from the user via an inputbox but nothing appears to happen, or the variable isn't being set, I'm not entirely sure which. I have my code below, any hints as to why this will not work for me?
Thanks!
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sr As IO.StreamReader
Dim age As Integer
Dim path As String
Try
sr = IO.File.OpenText("Ages.txt")
age = CInt(sr.ReadLine)
txtOutput.Text = "Age is " & age
Catch exc As IO.FileNotFoundException
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
Catch exc As InvalidCastException
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
Try
sr = IO.File.OpenText(path)
Finally
txtOutput.Text = "Age is " & age
End Try
Finally
Try
sr.Close()
Catch
End Try
End Try
End Sub

Your inner Try/Catch block should be inside the FileNotFoundException catch.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sr As IO.StreamReader
Dim age As Integer
Dim path As String
Try
sr = IO.File.OpenText("Ages.txt")
age = CInt(sr.ReadLine)
txtOutput.Text = "Age is " & age
Catch exc As IO.FileNotFoundException
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
Try
sr = IO.File.OpenText(path)
Finally
txtOutput.Text = "Age is " & age
End Try
Catch exc As InvalidCastException
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
Finally
Try
sr.Close()
Catch
End Try
End Try
End Sub
An even better solution would be...
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim age As Integer
Dim path As String = "Ages.txt"
Dim fileFound As Boolean = False
While Not IO.File.Exists(path)
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
End While
Using sr As IO.StreamReader = IO.File.OpenText(path)
If Integer.TryParse(sr.ReadLine, age) Then
txtOutput.Text = "Age is " & age
Else
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
End If
End Using
End Sub
This will first check if the file exists, and continue looping until the user enter ones that does. This allows you to remove the FileNotFoundException catch.
This also uses Integer.TryParse to check if the value was casted correctly, allowing you to remove the InvalidCastException catch.
Lastly, opening the reader with a Using statement eliminates the need for a finally/nested try-catch block, as Using implements this internally.

I would bet that the exception being thrown is not an IO.FileNotFoundException, so your InputBox code is never being hit. OpenText can throw quite a few types of exception. There are several ways you can go about doing this without an exception (File.Exists comes to mind), but to continue on this route I would change your exception handling to something like this:
Catch exc as Exception
If TypeOf exc Is InvalidCastException Then
'...
Else
path = InputBox(....)
End If
End Try

Related

Visual Basic System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.' It worked before but now it doesn't. What happen?

So, my code was working before, I never touched it since, I come back cause now I need it and for some reason it wont work. I also got an old back up to compare what was wrong, and the old back up didn't have a problem but the finalized version does. Here's the code, I made two forms:
Imports System.ComponentModel
Imports System.Text.RegularExpressions
Public Class Form1
Dim Chars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
Private Sub Label1_Click(sender As Object, e As EventArgs)
End Sub
Private Sub Employee_DataBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
'Save
'Me.Validate()
'Me.Employee_DataBindingSource.EndEdit()
'Me.TableAdapterManager.UpdateAll(Me.EmployeeDatabaseDataSet)
btnSave.PerformClick()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'EmployeeDatabaseDataSet1.Employee_Data' table. You can move, or remove it, as needed.
Me.Employee_DataTableAdapter1.Fill(Me.EmployeeDatabaseDataSet1.Employee_Data)
'TODO: This line of code loads data into the 'EmployeeDatabaseDataSet.Employee_Data' table. You can move, or remove it, as needed.
'Me.Employee_DataTableAdapter.Fill(Me.EmployeeDatabaseDataSet.Employee_Data)
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Application.Exit() 'Exits the application upon pressing the btnCancel
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Adds new profile
' MsgBox("You pressed Add New Profile")
Try
With btnAdd
If .Text = "Add New Profile" Then 'If the literal text of the button is equal to that, then we shall continue with the execution
Employee_DataBindingSource1.AddNew() 'Adds a new profile to the Access Database as it is the source
.Text = "Cancel" 'Changes the Text of the Button to show Cancel
Else
RefreshData()
.Text = "Add New Profile"
End If
End With
With txtLuxFirstName
If (.CanSelect) Then
.Text = String.Empty
.Select()
End If
End With
Catch ex As Exception 'If there is an error/exception
MsgBox("An Error Occured: " & ex.Message.ToString(), 'A message will pop up saying "An Error Occured : (Actual Error Identification)"
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Add new profile failed.") 'And will continue displaying the error information
End Try
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim par As String
par = "^([0-9a-zA-z]([-\.\w]*[0-9a-zA-Z])*#([0-9a-zA-z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"
If String.IsNullOrEmpty(txtLuxFirstName.Text) Or IsNumeric(txtLuxFirstName.Text) Or String.IsNullOrEmpty(txtLuxLastName.Text) Or IsNumeric(txtLuxLastName.Text) Or String.IsNullOrEmpty(txtEmail.Text) Or Regex.IsMatch(txtEmail.Text, par) Or String.IsNullOrEmpty(txtMobile.Text) Or txtMobile.Text = Chars Or String.IsNullOrEmpty(txtAddress.Text) Or String.IsNullOrEmpty(txtIncome.Text) Or txtIncome.Text = Chars Then
MessageBox.Show("Please enter the correct variables for the respective fields")
Else
Try
Dim result As DialogResult
result = MessageBox.Show("Do you want to save the selected profile?", "Save Profile",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If (result = DialogResult.Yes) Then
Validate()
Employee_DataBindingSource1.EndEdit()
TableAdapterManager1.UpdateAll(Me.EmployeeDatabaseDataSet1)
MessageBox.Show("The Profile has been saved successfully.",
"Save Profile", MessageBoxButtons.OK, MessageBoxIcon.Information)
RefreshData()
btnAdd.Text = "Add New Profile"
Else
Return
End If
Catch ex As Exception
MessageBox.Show("Save Profile Failed: " & ex.Message.ToString(),
"Save Profile", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
If MessageBox.Show("Do you want to permanently delete the selected record?",
"Delete Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question) Then
Employee_DataBindingSource1.RemoveCurrent()
Employee_DataBindingSource1.EndEdit()
Employee_DataTableAdapter1.Update(EmployeeDatabaseDataSet1.Employee_Data)
RefreshData()
MessageBox.Show("The Profile has been deleted successfully.",
"Delete Profile", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
MessageBox.Show("Delete Data Failed: " & ex.Message.ToString(),
"Delete Data", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub RefreshData()
Try
Me.Employee_DataBindingSource1.Filter = Nothing
Me.Employee_DataTableAdapter1.Fill(Me.EmployeeDatabaseDataSet1.Employee_Data)
Catch ex As Exception
MsgBox("Refresh Data Error")
End Try
End Sub
Private Sub btnJob_Click(sender As Object, e As EventArgs) Handles btnJob.Click
Form2.Show()
End Sub
End Class
When I run the code, the:
Me.Employee_DataTableAdapter1.Fill(Me.EmployeeDatabaseDataSet1.Employee_Data)
line of code gets an error which is in the question. This literally worked before Idk what happened.
And yes I connected it to the Access Database.

BC42104 error code how can I fix this error?

Warning BC42104: Variable 'pass' is used before it has been assigned a value. A null reference exception could result at runtime.
This is my code:
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim uname As String = ""
Dim pword As String
Dim username As String = ""
Dim pass As String
If TextBox1.Text = "" Or TextBox2.Text = "" Then
MsgBox("Please fill the info")
Else
uname = TextBox1.Text
pword = TextBox2.Text
Dim query As String = "Select Password From Register where Username= '" & uname & "';"
Dim dbsource As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gui\Documents\Database4.accdb"
Dim conn = New OleDbConnection(dbsource)
Dim cmd As New OleDbCommand(query, conn)
conn.Open()
Try
pass = cmd.ExecuteScalar().ToString
Catch ex As Exception
MsgBox("Username does not exit")
End Try
If (pword = pass) Then
MsgBox("Login success")
Reg.Show()
If Reg.Visible Then
Me.Hide()
End If
Else
MsgBox("login Failed")
TextBox1.Clear()
TextBox2.Clear()
End If
End If
End Sub
As the error is saying, you are not initializing the variable pass and under some condition, you may end up with using it.
To be exact, if the control lands in the 'catch' block, the variable 'pass' will not have any values, which means it is possible that If (pword = pass) statement is reached without this variable having any values.
To fix the error, just assign a null value or empty string to the variable at the point of initialization. For example use this statement:
Dim pass As String = "";

Stumped why I'm getting "System.ArgumentOutOfRangeException" error

I've run into a problem with a program for my Visual Basic class that has me stumped. The assignment is a Guessing Game, I'm to create a private sub that generates a random number within the bounds of a user input (ie... 1 - 100). I seem to have this functional with the exception of telling the computer to guess lower. Currently if I press "Higher" the game continues, but if I press "Lower" the error is thrown with "minValue cannot exceed maxValue". If the output in the text box is higher than my lownum variable, why am I getting this error?
The bolded code is the code I have written, everything else was provided.
Public Class frmGuess
Dim highNum As Integer
Dim lowNum As Integer
Dim guess As Integer
Private Sub frmGuess_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MessageBox.Show("Lets Play a Game!")
'Fixed the grammatical error below - "Think of an whole number" is incorrect.
MessageBox.Show("Think of a whole number -- DON'T TELL ME!")
MessageBox.Show("Now give me a range you want me to guess in... like 1 to 100.")
lowNum = InputBox("Whats the starting value?", "Lowest Value")
highNum = InputBox("Whats the ending value?", "Highest Value")
lblTitle.Text = "I am guessing a number between " & lowNum & " and " & highNum & "."
newGuess()
End Sub
**Sub newGuess()
'
' ITS GONE! OH NO!
'
'New Guess Sub - Calculates a response based on the input from user and recalculates responses to guess the number.
'Setting New Variables
Dim random As New Random
'Generating Response
txtGuess.Clear()
txtGuess.Text = random.Next(lowNum, highNum + 1)
End Sub**
Private Sub btnLower_Click(sender As Object, e As EventArgs) Handles btnLower.Click
highNum = guess - 1
newGuess()
End Sub
Private Sub btnHigher_Click(sender As Object, e As EventArgs) Handles btnHigher.Click
lowNum = guess + 1
newGuess()
End Sub
Private Sub btnCorrect_Click(sender As Object, e As EventArgs) Handles btnCorrect.Click
MessageBox.Show("I win. I told you I was awesome.")
Close()
End Sub
Private Sub txtGuess_TextChanged(sender As Object, e As EventArgs) Handles txtGuess.TextChanged
End Sub
End Class
Figured it out, the program functions as expected.

IOException Was Unhandled Error Help for Newbie

You'll have to excuse me for a repeat question but I just can't seem to understand the responses others have been posting. My coding skills are very limited (barely a year in vb 2006 and vs 2010)
I know that the sr has opened too many of the same file but I cant figure out a fix for it. Explaining it to me in simple concepts would be very helpful. Once again sorry for the newby-ness.
Project Explanation: Create a bowling league stats keeper. cmdRegisterBowler adds bowler name to a dat file (bowlers.dat). cmdEnterScores will write name and stats to games.dat file.
Private Sub cmdRegisterBowler_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegisterBowler.Click
'BOWLER REGISTRATION
Dim Person As String
Dim Team As String
txtName.Text.ToUpper()
txtTeam.Text.ToUpper()
Person = txtName.Text
Team = txtTeam.Text
If Person <> "" And Team <> "" Then
If IsInFile(Person & " " & Team) = True Then
MessageBox.Show(Person & " is already in the file.", "Error")
txtName.Clear()
txtTeam.Clear()
txtName.Focus()
Else
'swb = stream writer bowlers file
Dim swb As IO.StreamWriter = IO.File.AppendText("bowlers.dat")
swb.WriteLine(Person & " " & Team)
swb.Close()
MessageBox.Show(Person & " has been added to the file.", "Information Added")
txtName.Clear()
txtTeam.Clear()
txtName.Focus()
End If
Else
MessageBox.Show("You must enter a name.", "Information Incomplete")
End If
End Sub
Function IsInFile(ByVal person As String) As String
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
End Function
Private Sub cmdEnterScores_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEnterScores.Click
'SCORE ENTRY
Dim Person As String
Dim Team As String
Dim Score1 As Double
Dim Score2 As Double
Dim Score3 As Double
Dim Average As Double
Dim Display As String = "{0,-10} {1,10} {2,20} {3,10} {4,10} {5,10} {6,10}"
Dim Total As Double
Person = txtName2.Text
Team = txtTeam2.Text
Score1 = Val(txtFirstGame.Text)
Score2 = Val(txtSecondGame.Text)
Score3 = Val(txtThirdGame.Text)
Total = Score1 + Score2 + Score3
Average = Total / 3
Dim swb As IO.StreamWriter = IO.File.AppendText("bowlers.dat")
'Checks for blank entries
If Person <> "" Then
'Checks to see if person is registered
If IsNotInFile(Person) Then
Dim Response As Integer
' Displays a message box with the yes and no options to register bowler.
Response = MsgBox(Prompt:="The bowler you have entered is currently not registered. Would you like to do so?", Buttons:=vbYesNo)
'Yes button was selected. Bowler is then registered to bowlers.dat
If Response = vbYes Then
''swb = stream writer bowlers file
swb.WriteLine(Person & " " & Team)
swb.Close()
MessageBox.Show(Person & " has been added to the file.", "Information Added")
'The no button was selected. Focus is set to bowler registration group box
Else : Response = vbNo
txtName2.Clear()
txtTeam2.Clear()
txtFirstGame.Clear()
txtSecondGame.Clear()
txtThirdGame.Clear()
txtName.Focus()
End If
'If no then clears score entry group box and sets focus back to bowler registr
txtName.Clear()
txtName.Focus()
Else
'Write scores to games.dat file
'swg = stream writer games file
Dim swg As IO.StreamWriter = IO.File.AppendText("games.dat")
swg.WriteLine(Name & " " & Team & " " & Score1 & " " & Score2 & " " & Score3)
swg.Close()
MessageBox.Show(Person & "'s stats added to the file.", "Information Added")
txtName.Clear()
txtName.Focus()
Dim Display2 As String = "{0,-10} {1,10} {2,20} {3,10} {4,10} {5,10} {6,10}"
lstDisplay.Items.Add(String.Format(Display2, Person, Team, Score1, Score2, Score3, Total, Average))
End If
Else
MessageBox.Show("You must enter a name.", "Information Incomplete")
End If
End Sub
Function IsNotInFile(ByVal person As String) As String
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual <> person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
End Function
Heres all my code. Thanks for any help in advance.
I haven't used Visual Basic in quite a while, but I believe the solution is simple.
Basically, your interactions with the System.IO library are currently very optimistic. You should always wrap IO interactions within a TRY...CATCH...END TRY block.
Check it out here: MSDN Example of StreamReader.ReadLine
To illustrate more clearly my meaning, I've altered one of your functions here:
Function IsInFile(ByVal person As String) As String
Try
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
Catch ie as IOException
MessageBox.Show("Failed to search for " & person & " in file.", "Error")
Return false
End Try
End Function
I'd apply similar logic to surround all your interactions with Files within your code. I'd also recommend against using MessageBox to report errors -- it's okay for small projects, but for anything larger you're going to want to look up using a logging framework. Or build a debug console into your application that you can selective turn on or off via configuration.

Visual Basic Deleting Unmodified Files

The following code will extract files from one Folder and Place them another as you can see. But I am trying to delete the files that have not been modified in the past 3 months, and it does not delete any files at all.
Code:
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Try
Dim di As DirectoryInfo = New DirectoryInfo(sourceDirectory)
Dim fi As FileInfo() = di.GetFiles()
For Each currentFile As FileInfo In fi
File.Move(currentFile.FullName, Path.Combine(archiveDirectory, currentFile.Name))
Dim dt As DateTime = currentFile.LastWriteTime
' Add 3 months to the last write and check if it is less than today '
If dt.AddMonths(3) < DateTime.Today Then
File.Delete(currentFile.FullName)
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class

Resources