TNO
-
Total Posts
:
2094
- Scores: 36
-
Reward points
:
0
- Joined: 12/18/2004
- Location: Earth
-
Status: offline
|
How To FTP Upload a file
Tuesday, March 31, 2009 2:52 AM
( permalink)
This irritated me for a few hours since documentation on the web is quite horrible. Here is how to perform a basic FTP upload with a .NET console application:
Imports System
Imports System.Text
Imports System.Net
Imports System.IO
Module Module1
Sub Main()
Dim server As String = "127.0.0.1"
Dim username As String = "foo"
Dim password As String = "bar"
Dim port As Integer = 21
Dim targetFolder As String = "wwwroot"
Dim fileName As String = "C:\test.txt"
Dim passive As Boolean = False
Dim url As String = String.Format("ftp://{0}:{1}/{2}/{3}", server, port, targetFolder, fileName.Substring(fileName.LastIndexOf("\") + 1)) ' make sure you specify the filename and not the entire path or it will thrrow
Dim FTP As FtpWebRequest = CType(WebRequest.Create(url), FtpWebRequest)
With FTP
.Credentials = New NetworkCredential(username, password)
.KeepAlive = False
.UseBinary = False
.Method = WebRequestMethods.Ftp.UploadFile
.UsePassive = passive
Try
Using Writer As New BinaryWriter(.GetRequestStream())
Writer.Write(File.ReadAllBytes(fileName))
End Using
Catch ex As WebException
Throw ex
Finally
End Try
End With
End Sub
End Module
Probably the most important thing to remember is that the filename is used in two places. first its used to find where on your computer the file you want to upload is located at. Second you have to be sure to strip out that full path before you put it in the url variable so you have a proper file name on the server.
To iterate is human, to recurse divine. -- L. Peter Deutsch
|
|
|
|