Dim FtpHostname As String = "172.16.80.185"
Dim FtpUserName As String = "username"
Dim FtpPassWord As String = "password"
Dim FtpPort As String = "21"
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim response As Boolean
Dim folderServer As String = '/Newfolder/'
Dim pathFullName As String = 'D:\1234.jpg'
Dim filename As String = '1234.jpg'
Dim filenameNew As String = 'pic.jpg'
Try
' ====== Upload =======
response = cSftp.FTPuploadFile(folderServer , pathFullName , filename )
' ====== Delete =======
response = cSftp.FTPDeleteFile(folderServer & filename)
' ====== Rename =======
response = cSftp.FTPuploadFile(folderServer & filename, filenameNew )
Catch ex As Exception
End Try
End Sub
Function FTPuploadFile(ByVal folderServer As String, ByVal pathFullName As String, ByVal filename As String) As Boolean
' folderServer = '/Newfolder/'
' pathFullName = 'D:\1234.jpg'
' filename = '1234.jpg'
Try
Dim ftp As String = "ftp://" & FtpHostname & folderServer
Dim Request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(ftp & filename), System.Net.FtpWebRequest)
Request.Credentials = New System.Net.NetworkCredential(FtpUserName, FtpPassWord)
Request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
'Read File
Dim File() As Byte = System.IO.File.ReadAllBytes(pathFullName)
'Upload
Dim Strz As System.IO.Stream = Request.GetRequestStream()
Strz.Write(File, 0, File.Length)
Strz.Close()
Strz.Dispose()
Return True
Catch ex As Exception
'MessageBox.Show("เกิดความผิดพลาดของไฟล์: " & _pathName & vbNewLine & ex.Message, "Messsage")
Return False
End Try
End Function
' Delete File in Server Past FTP
Function FTPDeleteFile(ByVal folderServerFilename As String) As Boolean
Try
Dim filename As String = "ftp://" & FtpHostname & "/" & folderServerFilename
Dim ftpReq As FtpWebRequest = WebRequest.Create(filename)
ftpReq.Method = WebRequestMethods.Ftp.DeleteFile
ftpReq.Credentials = New NetworkCredential(FtpUserName, FtpPassWord)
Dim ftpResp As FtpWebResponse = ftpReq.GetResponse
Return True
Catch ex As Exception
'MsgBox("Error " + ex.ToString)
Return False
End Try
End Function
' Rename File in Server Past FTP
Private Sub RenameFileWord(ByVal NameOld As String, ByVal NameNew As String)
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
reqFTP = DirectCast(FtpWebRequest.Create(New Uri(FtpHostname & NameOld)), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.Rename
reqFTP.RenameTo = NameNew
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential(FtpUserName, FtpPassWord)
Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
ftpStream = response.GetResponseStream()
ftpStream.Close()
response.Close()
End Sub