Reader Level:
ARTICLE

Upload a File Using File Transfer Protocol (FTP)

On January 03, 2013 Articles | .NET 4.5
This article demonstrates how to upload a file using File Transfer Protocol (FTP).
  • 0
  • 0
  • 5829
Download Files:
 

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());
             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-the-file-on-FTP1.jpg

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

response.Close();

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.

upload-the-file-on-FTP.jpg

Article Extensions
Contents added by chandru selvam on May 10, 2013
Contents added by chandru selvam on May 10, 2013
Sachin Kalia

Hi Folks, I am Sachin Kalia .I work in .Net technologies and work in software company in 3 Pillar Global(Earlier Brickred Technologies).I share my thoughts about .Net and associated technologies ...

Personal Blog: http://www.dotnetpiper.com/
  • 80rank
  • 650K readers
  • 2times
COMMENT USING

Trending up