[VB.NET] 使用FtpWebRequest.ReName實現移動檔案功能

  FtpWebRequest類別沒有提供移動檔案的命令,但是可以透過WebRequestMethods.Ftp.Rename達成相同效果的功能。

Dim ftp_Request As FtpWebRequest = Nothing
Dim ftp_Response As FtpWebResponse = Nothing
Dim str_FtpAct As String = "XXX"
Dim str_FtpPwd As String = "XXX"
		
'Try to create backup folder. If folder already created, resume to backup. 
Try
    ftp_Request = CType(WebRequest.Create("D:/testfolder/backup"), FtpWebRequest)
    ftp_Request.Credentials = New NetworkCredential(str_FtpAct, str_FtpPwd)
    ftp_Request.Method = WebRequestMethods.Ftp.MakeDirectory
    ftp_Response = ftp_Request.GetResponse()
Catch ex_Web As WebException
    Dim ftp_ResponseEx As FtpWebResponse = ex_Web.Response
    Dim int_ErrCode As Integer = ftp_ResponseEx.StatusCode
    '550: Access is denied, means directory already exist
    If int_ErrCode <> 550 Then
        Console.WriteLine("Create Folder Failed!")
    End If
End Try
		
Try
    ftp_Request = CType(WebRequest.Create("D:/testfolder/test.txt"), FtpWebRequest)
    ftp_Request.Credentials = New NetworkCredential(str_FtpAct, str_FtpPwd)
    ftp_Request.Method = WebRequestMethods.Ftp.Rename
    ftp_Request.RenameTo = "../testfolder/backup/test.txt"
    ftp_Response = DirectCast(ftp_Request.GetResponse(), FtpWebResponse)

Catch webex As WebException
    'Get FTP Error code and exception status
    Dim ftp_ResponseEx As FtpWebResponse = webex.Response
    Dim int_FtpCode As Integer = ftp_ResponseEx.StatusCode

    'Do something

Finally
    If ftp_Response IsNot Nothing Then
        ftp_Response.Close()
    End If
End Try

 

參考資料