Below is a code snippet which demonstrates how to upload an FTP file using VB.net although the code apart for the syntax differences will be the same for csharp.
The function accepts the following parameters
- ftpAddress – this is the remote server address in the format FTP://server/foldername
- ftpUser – this is the user name with access to the FTP server
- ftpPassword – password for the ftpUser
- fileToUpload – file name and path you want to upload to the FTP folder
- targetFileName – file name you would like to upload your file as
- deleteAfterUpload – boolean value to set if you would like to delete the local file after uploading
- ExceptionInfo – if an exception occurs then the error is passed back by reference through this parameter
The function uses FTPWebRequest and FTPWebResponse classes from the System.Net namespace, it first checks the file name is in the correct format for upload, then makes the connection to the FTP server, then we need to split the file into a byte array and lastly we upload the file to the target file name.
Public Function UploadFTPFiles(ftpAddress As String, ftpUser As String, ftpPassword As String, fileToUpload As String, targetFileName As String, deleteAfterUpload As Boolean, ExceptionInfo As Exception) As Boolean Dim credential As NetworkCredential Try credential = New NetworkCredential(ftpUser, ftpPassword) If ftpAddress.EndsWith("/") = False Then ftpAddress = ftpAddress & "/" Dim sFtpFile As String = ftpAddress & fileToUpload Dim request As FtpWebRequest = DirectCast(WebRequest.Create(sFtpFile), FtpWebRequest) request.KeepAlive = False request.Method = WebRequestMethods.Ftp.UploadFile request.Credentials = credential request.UsePassive = False request.Timeout = (60 * 1000) * 3 '3 mins Using reader As New FileStream(fileToUpload, FileMode.Open) Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte reader.Read(buffer, 0, buffer.Length) reader.Close() request.ContentLength = buffer.Length Dim stream As Stream = request.GetRequestStream stream.Write(buffer, 0, buffer.Length) stream.Close() Using response As FtpWebResponse = DirectCast(request.GetResponse, FtpWebResponse) If deleteAfterUpload Then My.Computer.FileSystem.DeleteFile(fileToUpload) End If response.Close() End Using End Using Return True Catch ex As Exception ExceptionInfo = ex Return False Finally End Try End Function
There are of course other ways to upload to FTP sites from VB.net but the above is the one I have found most reliable.