2014-04-28 27 views
0

我是VB新手,所以我很感激這可能看起來像一個愚蠢的問題。錯誤處理VB中的OpenFileDialog

我使用下面的代碼來選擇從本地文件系統中的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) 

如何在沒有選擇文件的情況下優雅地處理此錯誤。

因此,在本質顯示一條消息:「沒有選擇的文件」

預先感謝您。

+0

地方'昏暗的解析器作爲新的FileIO.TextFieldParser(openFileDialog1.FileName)'在'If .. End If'條件 –

回答

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 

這將導致你的錯誤