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.

You need to add a reference of 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());
             request.ContentLength = fileContents.Length; 
            Stream requestStream = request.GetRequestStream();
             requestStream.Write(fileContents, 0, fileContents.Length);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);



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


The 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.