Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Me.Show()
Application.DoEvents()
If My.Computer.FileSystem.DirectoryExists("C:\Temp\") = False Then
My.Computer.FileSystem.CreateDirectory("C:\Temp")
End If
My.Computer.FileSystem.WriteAllText("C:\Temp\Temp.tmp", "Temp", False)
FtpUpload("C:\Temp\Temp.tmp", "ftp://Example.com/", "Username", "Password")
End Sub
Private Sub FtpUpload(ByVal PathAndFilenameToSendString As String, FtpServerUrlString As String, FtpUsernameString As String, FtpPasswordString As String)
If FtpServerUrlString.StartsWith("ftp://", True, Nothing) = False Then
FtpServerUrlString = "ftp://" & FtpServerUrlString
End If
If FtpServerUrlString.EndsWith("/") = False Then
FtpServerUrlString &= "/"
End If
Dim FileToSendInfo As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(PathAndFilenameToSendString)
If FileToSendInfo.Exists = False Then
System.Diagnostics.Debug.WriteLine("File does not exist: " & FileToSendInfo.FullName)
Exit Sub
End If
FtpServerUrlString &= FileToSendInfo.Name
Dim FtpServerCredentials As New System.Net.NetworkCredential(FtpUsernameString, FtpPasswordString)
Dim FtpWebRequest As Net.FtpWebRequest = DirectCast(Net.WebRequest.Create(FtpServerUrlString), Net.FtpWebRequest)
FtpWebRequest.UsePassive = False
FtpWebRequest.Method = Net.WebRequestMethods.Ftp.UploadFile
FtpWebRequest.Credentials = FtpServerCredentials
Dim FileStreamReader As New System.IO.FileStream(PathAndFilenameToSendString, System.IO.FileMode.Open)
Dim FileStreamBuffer(Convert.ToInt32(FileStreamReader.Length - 1)) As Byte
FileStreamReader.Read(FileStreamBuffer, 0, FileStreamBuffer.Length)
FileStreamReader.Close()
FtpWebRequest.ContentLength = FileStreamBuffer.Length
System.Diagnostics.Debug.WriteLine("Sending file: " & FtpServerUrlString)
Try
Dim FileStream As System.IO.Stream = FtpWebRequest.GetRequestStream
FileStream.Write(FileStreamBuffer, 0, FileStreamBuffer.Length)
FileStream.Close()
Catch ExceptionError As Exception
System.Diagnostics.Debug.WriteLine(ExceptionError.Message)
Exit Sub
End Try
Dim FtpServerResponse As Net.FtpWebResponse = DirectCast(FtpWebRequest.GetResponse, Net.FtpWebResponse)
System.Diagnostics.Debug.Write("Server reports: " & Trim(FtpServerResponse.StatusDescription))
If FtpServerResponse.StatusCode = System.Net.FtpStatusCode.ClosingData Then
Kill(PathAndFilenameToSendString)
System.Diagnostics.Debug.WriteLine("Sent file deleted: " & PathAndFilenameToSendString)
End If
FtpServerResponse.Close()
End Sub
Tips and tricks for .NET using ASP and VB code.
Send a file via FTP
Subscribe to:
Post Comments (Atom)
You programmers never cease to amaze me. I've tried to wrap my head around this stuff, but it just won't take. But I find it amazing...
ReplyDelete