在VB中处理OpenFileDialog时出错

时间:2014-04-28 09:36:23

标签: vb.net error-handling openfiledialog

我是VB的新手,所以我很欣赏这看起来像是一个愚蠢的问题。

我使用以下代码从本地文件系统中选择CSV文件。

    Dim openFileDialog1 As New OpenFileDialog

    openFileDialog1.InitialDirectory = "c:\uploads"
    openFileDialog1.Filter = "CSV files (*.csv)|*.csv"
    openFileDialog1.FilterIndex = 2
    openFileDialog1.RestoreDirectory = True


    If openFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then

    End If


        '--TextField Parser is used to read the files 
        Dim parser As New FileIO.TextFieldParser(openFileDialog1.FileName)

如果未选择文件,如何正常地发出此错误。

因此,实质上会显示一条消息,说明"没有选择文件"

提前谢谢。

1 个答案:

答案 0 :(得分:0)

 Dim openFileDialog1 As New OpenFileDialog
    Dim strFileName As String
    openFileDialog1.InitialDirectory = "c:\uploads"
    openFileDialog1.Filter = "CSV files (*.csv)|*.csv"
    openFileDialog1.FilterIndex = 2
    openFileDialog1.RestoreDirectory = True

    If openFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        strFiilename = openFileDialog1.FileName
        If strFileName <> "" Then
            'file is selected
        Dim parser As New FileIO.TextFieldParser(strFiilename)
        Else
            MsgBox("No File Selected")
        End If
    End If

我认为无需检查此strFileName因为您提出了问题

Dim parser As New FileIO.TextFieldParser(openFileDialog1.FileName)

If openFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
endif

这将导致您的错误