user3365878
user3365878

Reputation: 1

IOException was unhandled. Bad file name or number

I wrote this to read a selected index from a file and display its details but I'm having the error stated in the title.

My code:

'Declare variables
Dim OrdersFile As String
Dim NumRecsFound As Integer
Dim orderString As String
Dim searchID As Integer

'Find the selected order ID
orderString = lstOrder.Text
searchID = Val(Microsoft.VisualBasic.Left(orderString, 10))

'Set up the path to the orders file
OrdersFile = Application.StartupPath & "/orders.dat"

'Open the orders file in random access mode
FileOpen(1, OrdersFile, OpenMode.Random, , , Len(OrderRec))
'For each record in the file
RecPos = 1
'Read in every record until the end of the file is reached
Do While Not EOF(1)
    FileGet(1, OrderRec, RecPos)

    'If the record matches selected order, display the order file
    If OrderRec.OrderID = searchID Then
        NumRecsFound = NumRecsFound + 1

        With OrderRec
            txtOrderID.Text = .OrderID
            txtOrderDate.Text = .OrderDate
            txtPrice.Text = .Price
            cmbCustomers.Text = .CustomerID
            cmbPizza.Text = .PizzaID
        End With
    End If

    'Lock fields until edit is selected
    txtOrderID.Enabled = False
    txtFee.Enabled = False
    txtOrderDate.Enabled = False
    txtStatus.Enabled = False
    txtPrice.Enabled = False
    cmbCustomers.Enabled = False
    cmbPizza.Enabled = False

    'Close the orders file and leave the subroutine
    FileClose(1)

    'If the records don't match then get the next record
    RecPos = RecPos + 1
Loop

'If no records are found then output message and close the file
If NumRecsFound = 0 Then
    MsgBox("Order " & searchID & " could not be found. Please try again.")
    FileClose(1)
End If
FileClose(1)

the error appears in line 19; "Do While Not EOF(1)"

Any help will be appreciated. Thanks.

Upvotes: 0

Views: 1004

Answers (1)

Steve
Steve

Reputation: 216313

You say the error is on the line

Do While Not EOF(1)
    FileGet(1, OrderRec, RecPos)
    .......

but you have this

   'Close the orders file and leave the subroutine
    FileClose(1)

    'If the records don't match then get the next record
    RecPos = RecPos + 1
Loop

So if you have more than one record, at the second loop your code fails with the mentioned error

Move the FleClose(1) call outside the loop when you have really finished to read your records....
Of course this leaves the problem how to handle with more than one record.

Finally, we are in VB.NET here, the old VB6 function should be dumped as soon as possible. So, unless you are just maintaining an old project, take some time to change this code to use

string.Substring
Int32.TryParse
StreamReader
Using Statement

Feel free to add .....

Upvotes: 2

Related Questions