IOException未处理.文件名或编号不正确



我写这篇文章是为了从文件中读取选定的索引并显示其详细信息,但标题中指出了错误。

我的代码:

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

错误出现在第19行;"Do While Not EOF(1)">

任何帮助都将不胜感激。谢谢

您说错误在线上

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

但是你有这个

'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

因此,如果您有多个记录,在第二个循环中,您的代码将失败,并出现上述错误

当您真正完成读取记录时,将FleClos(1)调用移动到循环之外
当然,这就留下了如何处理多个记录的问题。

最后,我们在VB.NET中,旧的VB6函数应该尽快转储。所以,除非你只是在维护一个旧项目,否则需要一些时间来更改此代码以使用

string.Substring
Int32.TryParse
StreamReader
使用语句

请随意添加。。。。。