IOException未处理。文件名或编号错误

时间:2014-02-28 17:26:52

标签: vb.net 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行; “不做EOF(1)”

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

1 个答案:

答案 0 :(得分:2)

你说错误就行了

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

因此,如果您有多个记录,则在第二个循环中,您的代码将失败并显示错误

当你真正完成阅读你的记录后,将FleClose(1)调用移到循环外面。
当然,这就留下了如何处理多个记录的问题。

最后,我们在VB.NET中,旧的VB6函数应该尽快转储。因此,除非您只是维护旧项目,否则请花些时间更改此代码以使用

string.Substring
Int32.TryParse
StreamReader
Using Statement

随意添加.....