有人可以告诉我为什么下面的函数总是返回true,即使有问题的FTP目录不存在吗?
我传入的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 :(得分: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”的目录,您可以使用它来触发未找到的目录。)
答案 1 :(得分: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
我希望我可以帮助...