Uploading A File To FTP
Uploading A File To FTP
In order to upload a file using FTP details, one should know the servers FTP URL, FTP username and FTP password. We can achieve the file uploading task by using the below three inbuilt classes of .NET: FtpWebRequest, WebRequestMethods, and NetworkCredential . To start with the coding part. First we need to import the below namespaces
using System.IO; using System.Net;
Note: Please replace @absolutepath, @ftpurl, ftpusername, @ftppassword with your actual values. Copy the below code into your class:
private static void UploadFileToFTP(string source) { try { string filename = Path.GetFileName(source); string ftpfullpath = ftpurl; FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); ftp.KeepAlive = true; ftp.UseBinary = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; FileStream fs = File.OpenRead(source); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); } catch (Exception ex) { throw ex; } }
The final point will be calling the above procedure by using the below code on whatever event you want the operation to be performed.
UploadFileToFTP(sourcefilepath);