Simple Steps to FTP Upload Files

File Transfer Protocol (FTP) is a network protocol used to transfer files between computers and networks.
The FTP Url designates a file or a directory on an Internet Host that is accessible using FTP Protocol.
Normally, FTP Url is formatted: “ftp://”+ username + host + port + directory + filename

The syntax of FTP Url includes:

  • Host – fully qualified domain name of network host or IP Address (e.g. 172.0.0.1)
  • Port number to connect to – NOTE: if omitted, it defaults to 21
  • Username (user id) on the host
  • Password corresponding to the username

Here is a simple way to upload file to an FTP server:
1. Create an FtpWebRequest and pass in your FTP Url

FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create( "ftp://" + ftpPath + "/" + filename);
ftpClient.Credentials = new NetworkCredential( ftpUserName, ftpPassword );
ftpClient.Method = WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
ftpClient.ContentLength = file.Length;

2. Copy the contents of the file to the request stream using GetRequestStream().
Do not forget to close the Stream.

Byte[] buffer = new byte[file.Length + 1];
int bytes = 0;
int totalBytes = (int)file.Length;
FileStream fileStream = file.OpenRead();

Stream stream = ftpClient.GetRequestStream();
while ( totalBytes > 0 )
{
bytes = fileStream.Read( buffer, 0, buffer.Length );
stream.Write( buffer, 0, bytes );
totalBytes = totalBytes - bytes;
}
 //fs.Flush();
fileStream.Close();
stream.Close();

3. To finish the process, we need to close the ftpClient’s WebResponse.

FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
uploadResponse.Close();

Error Handling and other Gotcha’s

  • It is important we surround our code with try catch block because we need to make sure we protect the users from Exceptions like invalid credentials, etc.
    This is handled using the ftpClient’s response’s StatusCode

    catch ( WebException ex )
    {
        FtpWebResponse response = (FtpWebResponse)ex.Response;
        switch ( response.StatusCode )
           {
              case FtpStatusCode.NotLoggedIn:
              Debug.WriteLine = "You entered invalid username/password. Try again.";
              break;
    
              default:
              Debug.WriteLine = "The server is inaccessible or taking too long to respond.";
              break;
            }
    }
    
  • When creating FtpWebRequest and giving it the path (for example): “ftp://host:port/{directoryName}/{filename}, we need to make sure that {directoryName} has been created/should exist or it will throw an exception on GetRequestStream().

    Example:

    1. Create the directory, first.

     string directoryPath = "ftp://" + ftpPath + "/" + directory.Name;
     try
       {
        var request = (FtpWebRequest)FtpWebRequest.Create( directoryPath );
        request.Method = WebRequestMethods.Ftp.MakeDirectory;
        request.Credentials = new NetworkCredential( ftpUserName, ftpPassword );
        var uploadResponse = (FtpWebResponse)request.GetResponse();
        uploadResponse.Close();
       }
    

    2. Create FtpWebRequest and include directory to file path.

     var ftpClient = (FtpWebRequest)FtpWebRequest.Create( "ftp://" + ftpPath + "/"+ directory.Name + file.Name);
    

One thought on “Simple Steps to FTP Upload Files

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>