2016-05-07 39 views
0

目的:的FtpWebRequest:創建嵌套的目錄(本地VS遠程)

我要上傳的文件之前,確保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如果目錄電子設備的創造不止一個。

我的問題是爲什麼本地服務器不會出現此問題?我是否必須在遠程服務器上分別創建每個嵌套的目錄?


其他信息+第二個問題:

這是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%準確的,因爲我在上面的評論中提到過,所以請讓我知道你是否有更準確的方法。

回答

0

我已經決定使用單獨創建路徑的每個文件夾另一個功能:

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