2013-07-17 145 views
1

有人可以告诉我为什么下面的函数总是返回true,即使FTP目录不存在?VB.NET - 检查FTP目录是否总是返回true

directoryURL的我传递的值是以下形式:

ftp://ip_address/directory/subdirectory/

和具有后斜线。

Public Function DoesDirectoryExist(directoryUrl As String) As Boolean 
    ' Check that the target URL is properly formatted 
    If Not directoryUrl.StartsWith("ftp://") Then directoryUrl = "ftp://" & directoryUrl 

    ' Create a web request 
    Dim request As FtpWebRequest = DirectCast(WebRequest.Create(directoryUrl), FtpWebRequest) 
    request.Credentials = New NetworkCredential(_userName, _password) 
    request.Method = WebRequestMethods.Ftp.ListDirectory 

    ' Try and list the contents of the directory 
    Try 
    Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) 
     ' We have been succesful so the directory exists 
     Return True 
    End Using 
    Catch ex As WebException 
    Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse) 
    If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then 
     Return False 
    Else 
     Throw New ApplicationException("Unable to determine if FTP directory exists.") 
    End If 
    End Try 
End Function 
+0

是否状态代码('response.StatusCode')不同如果该目录存在或没有? – Matt

+0

状态码始终为200. –

回答

0

奇怪。这对我有用(我没有提出请求,但我想这应该不重要)。这是我通常依赖于代码:

Dim response As FtpWebResponse = request.GetResponse() 
Using (response) 
    found = True 
End Using 

的替代已被阅读目录列表:

Using sr As New System.IO.StreamReader(response.GetResponseStream()) 
    Using sw As New System.IO.StreamWriter("tempfile", False) 
     sw.Write(sr.ReadToEnd()) 
    End Using 
End Using 

在最坏的情况下,它应该帮助你解决这个问题(例如,它总是会创建一个名为“ghost”的目录,您可以使用它来触发未找到的目录)。

+0

我可能不得不放弃其他选择。任何分析响应的好建议? –

+0

响应正文如下所示:“

200 Type set to I 200 Port command successful 550 File not found 
” - 所以响应中会返回一个550,但代码设置不正确。 –

+0

我刚刚检查了550码的响应正文。有点粗糙它有效。谢谢。 –

0

方法1

Public Function DirectoryExists(directory As String) As Boolean 
Dim directoryExists__1 As Boolean 

Dim request = DirectCast(WebRequest.Create(directory), FtpWebRequest) 
request.Method = WebRequestMethods.Ftp.ListDirectory 
request.Credentials = New NetworkCredential("user", "pass") 

Try 
    Using request.GetResponse() 
     directoryExists__1 = True 
    End Using 
Catch generatedExceptionName As WebException 
    directoryExists__1 = False 
End Try 

Return directoryExists__1 
End Function 

方法2

If Not DirectoryExists("ftp://" + FTPSettings.IP + "/" + lo_ScreenShotPath) Then 
     reqFTP = DirectCast(FtpWebRequest.Create(New Uri("ftp://" + FTPSettings.IP + "/" + lo_ScreenShotPath)), FtpWebRequest) 
End If 

我希望我可以帮助这个...