1

谁能告诉我为什么下面的函数总是返回 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
4

2 回答 2

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”的目录,您可能会使用它来触发未找到)。

于 2013-07-17T16:09:42.390 回答
0

方法一

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

方法二

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

我希望我能帮助这个...

于 2013-11-13T11:11:21.020 回答