Copy files from local server folder to FTP server

In this post i will show how to copy files from local server folder a FTP server folder using FtpWebRequest class.
 private void FTPUpload(string filename, string ftpServerIP1)
   {
       string ftpUserID1 = "";//Ftp UserId
       string ftpPassword1=""//ftp password
       FileInfo fileInf = new FileInfo(filename);
       string uri = "ftp://" + ftpServerIP1 + "/" + fileInf.Name;
       FtpWebRequest reqFTP;
       // Create FtpWebRequest object from the Uri provided
       reqFTP = (FtpWebRequest)FtpWebRequest.Create
       (new Uri("ftp://" + ftpServerIP1 + "/" + fileInf.Name));
       // Provide the WebPermission Credintials 
       reqFTP.Credentials = new NetworkCredential(ftpUserID1, ftpPassword1);
       // By default KeepAlive is true, where the control connection
       // is not closed after a command is executed. 
       reqFTP.KeepAlive = false;
       // Specify the command to be executed. 
       reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
       // Specify the data transfer type. 
       reqFTP.UseBinary = true;
       // Notify the server about the size of the uploaded file
       reqFTP.ContentLength = fileInf.Length;
       int buffLength = 500447300;
       byte[] buff = new byte[buffLength];

       int contentLen;
       // Opens a file stream (System.IO.FileStream) to read the file
       // to be uploaded 
       FileStream fs = fileInf.OpenRead();
       try
       {
           // Stream to which the file to be upload is written 
           Stream strm = reqFTP.GetRequestStream();
           // Read from the file stream 2kb at a time
           contentLen = fs.Read(buff, 0, buffLength);
           // Till Stream content endswhile (contentLen != 0) 
           {

               // Write Content from the file stream to the FTP Upload
               // Stream

               strm.Write(buff, 0, contentLen);
               contentLen = fs.Read(buff, 0, buffLength);
           }

           strm.Close();
           fs.Close();

       }
       catch (Exception ex)
       {

           throw new Exception(ex.Message);
       }

   }

2 comments:

  1. Thanks for the example. I am trying to implement it, but I am getting the error: "File Save error: System.IO.FileNotFoundException: Could not find file 'Test document.doc'. File name: 'Test document.doc' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileInfo.get_Length() ..." What am I doing wrong?

    ReplyDelete
  2. Hi,
    I have tested all the code on my local system.from the exception it's look that problem is in file path.Debug the code and check the file path also ping the ftp server.

    ReplyDelete