目的:
我想确保在上传文件之前存在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 :(得分: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