FtpWebRequest:创建嵌套目录(本地与远程)

FtpWebRequest: create nested directories (local vs remote)

Objective:

我想在上传文件之前确保 FTP 路径存在,如果不存在 ==> 创建它。

我使用的代码:

Dim ftpPath As String = "ftp://----------/ParentDir/SubFolder1/SubFolder2"
If Not FTPDirExists(ftpPath) Then
    CreateFTPDir(ftpPath)
End If

其中 CreateFTPDir 是:

Private Sub CreateFTPDir(DirPath As String)
    Dim request As FtpWebRequest = FtpWebRequest.Create(DirPath)
    request.Credentials = New NetworkCredential("UserName", "Password")
    request.Method = WebRequestMethods.Ftp.MakeDirectory
    request.Proxy = Nothing
    request.KeepAlive = True
    Try
        Dim resp As FtpWebResponse = request.GetResponse()
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
End Sub

现在,当我在本地 FTP 服务器(使用 FileZilla 创建)上测试此代码时,无论嵌套目录的数量如何,它都会创建路径。但是 当我在实际(远程)FTP 服务器上使用它时,它抛出以下异常:The remote server returned an error: (550) File unavailable 如果要创建的目录不止一个。

我的问题是为什么本地服务器没有出现这个问题?我是否必须在远程服务器上分别创建每个 nested 目录?


补充信息 + 第二个问题:

这是我正在使用的 FTPDirExists 函数(经过大量搜索后我能想到的最好的函数):

Private Function FTPDirExists(DirPath As String) As Boolean
    DirPath &= If(DirPath.EndsWith("/"), "", "/")
    Dim request As FtpWebRequest = FtpWebRequest.Create(DirPath)
    request.Credentials = New NetworkCredential("UserName", "Password")
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
    request.Proxy = Nothing
    request.KeepAlive = True
    Try
        Using resp As FtpWebResponse = request.GetResponse()
            Return True
        End Using
    Catch ex As WebException
        Dim resp As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse)
        If resp.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
            Return False ' ==> Unfortunately will return false for other reasons (like no permission).
        Else
            Return False ' ==> Don't bother about this.
        End If
    End Try
End Function

我在上面的评论中提到的不是 100% 准确,所以如果您有更准确的方法,请告诉我。

我决定使用另一个函数来分别创建路径的每个文件夹:

Public Shared Sub CreatePath(RootPath As String, PathToCreate As String, Cred As NetworkCredential)
    Dim request As FtpWebRequest
    Dim subDirs As String() = PathToCreate.Split("/"c)
    Dim currentDir As String = If(RootPath.EndsWith("/"), RootPath.Substring(0, RootPath.Length - 1), RootPath)
    For Each subDir As String In subDirs
        currentDir &= "/" & subDir

        request = DirectCast(FtpWebRequest.Create(currentDir), FtpWebRequest)
        request.Credentials = Cred
        request.Method = WebRequestMethods.Ftp.MakeDirectory
        request.Proxy = Nothing
        Try
            Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
            response.Close()
        Catch ex As Exception

        End Try
    Next
End Sub