17/06/2015 by Nitesh

Upload Files to FTP Server in C#

Friends,

In some of my previous articles, I wrote about with How To List Files From FTP Server, How To Delete File From FTP Server, How To Download File From FTP Server. In this article, we will see how can we upload a file to FTP server using C# from our local hard disk.

private void UploadFileToFTP()
{
   FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
               
   ftpReq.UseBinary = true;
   ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
   ftpReq.Credentials = new NetworkCredential("user", "pass");

   byte[] b = File.ReadAllBytes(@"E:\sample.txt");
   ftpReq.ContentLength = b.Length;
   using (Stream s = ftpReq.GetRequestStream())
   {
        s.Write(b, 0, b.Length);
   }

   FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

   if (ftpResp != null)
   {
         if(ftpResp.StatusDescription.StartsWith("226"))
         {
              Console.WriteLine("File Uploaded.");
         }
   }
}

The above code reads a text file names “sample.txt” from your hard disk and uploads it to the root folder of the server named “www.server.com”. If you see the code,we created an object of FtpWebRequest class and this time, we passed the RequestMethod as UploadFile. This command tells the CLR to upload the mentioned file from the local system to server. It is important to note that we need to tell the file name after the server name to define the file name that will be used for uploading the file. Another thing to note is we need to set the UseBinary property of the FTPWebRequest object to true to be able to download files and view its contents properly.

Hope this post will help you in uploading files to any FTP server in C#! Keep learning and sharing! Cheers!

#C##Ftp#Winforms