2014-07-06 48 views
0

所以我想上傳文件到我的FTP,雖然我想要它來測試FTP的細節是否正確。我發現下面的代碼,雖然它的工作原理雖然它顯示'存在'當它連接,但是當它無法連接[與假的細節]它不會做任何事情(我想要一個錯誤顯示說它不能連接)VB.NET測試FTP連接

Imports System.Net 

    Dim request = _ 
    DirectCast(WebRequest.Create _ 
    ("ftp://ftp.example.com/folder_here/"), FtpWebRequest) 

    request.Credentials = _ 
    New NetworkCredential("user_here", "pass_here") 

    request.Method = WebRequestMethods.Ftp.ListDirectory 

    Try 
     Using response As FtpWebResponse = _ 
     DirectCast(request.GetResponse(), FtpWebResponse) 
      ' Folder exists here 
      MsgBox("exists!") 
     End Using 

    Catch ex As WebException 
     Dim response As FtpWebResponse = _ 
     DirectCast(ex.Response, FtpWebResponse) 
     'Does not exist 
     If response.StatusCode = _ 
     FtpStatusCode.ActionNotTakenFileUnavailable Then 
      MsgBox("Doesn't exist!") 
     End If 
    End Try 

我該如何解決這個問題?

回答

0

我認爲使用塊可能會捕捉異常。試試這個代替

Try 
    Dim response As FtpWebResponse = _ 
    DirectCast(request.GetResponse(), FtpWebResponse) 
     ' Folder exists here 
    MsgBox("exists!") 

Catch ex As WebException 
    Dim response As FtpWebResponse = _ 
    DirectCast(ex.Response, FtpWebResponse) 
    'Does not exist 
    If response.StatusCode = _ 
    FtpStatusCode.ActionNotTakenFileUnavailable Then 
     MsgBox("Doesn't exist!") 
    End If 
End Try