Upload a File Using File Transfer Protocol (FTP)

There are a few things you need to consider during implementation. I've also attached the code segment to understand things better and in a more convenient way for all geeks, who want to implement it.

You need to add a reference to System.Net to use the FtpWebRequest object.

The code is given below to upload the file using FTP.

string PureFileName = new FileInfo("TotalAmount").Name;
string uploadUrl = String.Format("{0}/{1}/{2}", "ftp://ftp.sachinkalia.com", "sachin_folder", PureFileName);
FtpWebRequest request = (FtpWebRequest) WebRequest.Create(uploadUrl);
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("username", "password");
request.Proxy = null;
request.KeepAlive = true;
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.UploadFile;

// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(@"D:\Sapmle applications\TotalAmount.txt");
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

Upload file

The status description given above describes that the data (File) has been uploaded to the FTP site with the "Transfer OK" message.

response.Close();

A similar approach is for deleting any file from FTP, whilst the only difference you are required to set is WebRequestMethods.Ftp.DeleteFile. The code is available below.

FTP