Click here to Skip to main content
15,039,149 members
Articles / General Programming / Internet
Posted 1 Dec 2011


80 bookmarked

File Transfer Protocol (FTP) Client

Rate me:
Please Sign up or sign in to vote.
4.83/5 (20 votes)
1 Dec 2011CPOL7 min read
Connect to FTP server, and download, upload, rename, and delete files or directories.

Image 1


I know there are a lot of FTP client programs available on the Internet. But we also need to understand FTP (File Transfer Protocol)'s substructure. So this Open Source project will lead your way when trying to learn about FTP. This program's interface look like FileZilla. FileZilla is so popular but it has some bugs. It all started when I tried to open my blog. I needed to connect to my server via FTP, send files, download files, etc. So I decided to write my own application to handle all of this. FileZilla is good enough but it's not mine.


Let's see what we know. We know FTP is a standard TCP based network protocol used to transfer files from one host to another host. And it's a client-server architecture.


FTP programs were based on command-lines. We can still use "cmd.exe" to connect to FTP servers because FTP works with commands. For example, to send a file, we can use "stor" from the command line. In order to do all of these, the FTP server needs to be running and waiting for incoming requests. We can better understand FTP from Wikipedia: "The client computer is able to communicate with the server on port 21 and it's called the control connection. It remains open for the duration of the session, with a second connection, called the data connection either opened by the server from its port 20 to a negotiated client port (active mode) or opened by the client from an arbitrary port to a negotiated server port (passive mode) as required to transfer file data. The control connection is used for session administration (i.e., commands, identification, passwords) exchanged between the client and server using a Telnet-like protocol. For example, "RETR filename" would transfer the specified file from the server to the client. Due to this two-port structure, FTP is considered an out-of-band protocol, as opposed to an in-band protocol such as HTTP."


"The server responds on the control connection with three digit status codes in ASCII with an optional text message, for example "200" (or "200 OK.") means that the last command was successful. The numbers represent the code number and the optional text represents explanations (e.g., <OK>) or needed parameters (e.g., <Need account for storing file>)." So what do we need to do? It's so clear. Send command, receive "OK" command, send data, receive data, and that's all. But first we should prepare the server. FTP servers can be run in "active" or "passive" mode. Active mode is a server based connection and passive is a client based connection. Let's see more.

In active connections, clients send the IP and port to the server then the server will try to connect to the client. But it could be denied by the client because of firewalls. We all use antivirus software or Windows Firewalls, right? Now let's see passive mode.

In passive connections, the server sends its IP and port to the client with a "PASV" command then the client can try to connect the server with this IP. It's a very usable way to send files. When we try to send a file, we should use the "PASV" mode first. And as you know, most protocols like FTP, HTTP use ASCII characters when trying to get something because it's a global mode. Because it's global, we will use this mode. And you can get the FTP command list from this URL:

Using the code

Now we are ready to prepare our application. Let's code something useful :) First of all, we need an "Open File dialog" but integrated with our Form.

File Explorer component

We need a file explorer component to see our files to send to the FTP server with our application's interface. Open a new project of type "Windows Forms User Control Library".


It'll look like this. Now we need a treeview. A few buttons. And a search feature.

TreeNode nodeD = new TreeNode();
nodeD.Tag = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
nodeD.Text = "Desktop";
nodeD.ImageIndex = 10;
nodeD.SelectedImageIndex = 10;

Like shown in this code, we should add the main nodes first, "My Documents", "My Computer", etc. Then get the sub directories.

string[] dirList;
dirList = Directory.GetDirectories(parentNode.Tag.ToString());
if (dirList.Length == parentNode.Nodes.Count)
for (int i = 0; i < dirList.Length; i++)
    node = new TreeNode();
    node.Tag = dirList[i]; 
    node.Text = dirList[i].Substring(dirList[i].LastIndexOf(@"\") + 1);
    node.ImageIndex = 1;

You can get the complete code from the link above. We should track the click, down events implemented by the mouse.

Now we have a file explorer, and all the needed information about FTP and Visual Studio.

First of all, we need to connect to the server. What should we do?

FTPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
AppendText(rchLog,"Status : Resolving IP Address\n",Color.Red);
remoteAddress = Dns.GetHostEntry(Server).AddressList[0];
AppendText(rchLog, "Status : IP Address Found ->" + remoteAddress.ToString() + "\n", Color.Red);
addrEndPoint = new IPEndPoint(remoteAddress, Port);
AppendText(rchLog,"Status : EndPoint Found ->" + addrEndPoint.ToString() + "\n", Color.Red);

Yes, we need an open socket so connect to our server. Now we can send our commands:

AppendText(rchLog, "Command : " + msg + "\n", Color.Blue);
Byte[] CommandBytes = Encoding.ASCII.GetBytes((msg + "\r\n").ToCharArray());
FTPSocket.Send(CommandBytes, CommandBytes.Length, 0);
//read Response

We send our command to the server and it will answer but in its own language. We need to understand it. The answer include a 3 digit code and an explanation.

private string SplitResponse()
        while (true)
            Bytes = FTPSocket.Receive(Buffer, Buffer.Length, 0); //Number Of Bytes (Count)
            StatusMessage += Encoding.ASCII.GetString(Buffer, 0, Bytes); //Convert to String
            if (Bytes < Buffer.Length)  //End Of Response
        string[] msg = StatusMessage.Split('\n');
        if (StatusMessage.Length > 2)
            StatusMessage = msg[msg.Length - 2];  //Remove Last \n
            StatusMessage = msg[0];
        if (!StatusMessage.Substring(3, 1).Equals(" "))
            return SplitResponse();
        for (int i = 0; i < msg.Length - 1; i++)
            AppendText(rchLog, "Response : " + msg[i] + "\n", Color.Green);
        return StatusMessage;
    catch(Exception ex)
        AppendText(rchLog, "Status : ERROR. " +ex.Message+ "\n", Color.Red);
        return "";

Yes, that's all .Now we can download, upload, rename, or delete everything :)

List of FTP commands

For easy reference I am including the command list from Wikipedia:

ABORAbort an active file transfer
ACCTAccount information
ADATRFC 2228Authentication/Security data
ALLOAllocate sufficient disk space to receive a file
AUTHRFC 2228Authentication/Security mechanism
CCCRFC 2228Clear command channel
CDUPRFC 959Change to parent directory
CONFRFC 2228Confidentiality protection command
CWDRFC 697Change working directory
DELEDelete file
ENCRFC 2228Privacy protected channel
EPRTRFC 2428Specifies an extended address and port to which the server should connect
EPSVRFC 2428Enter extended passive mode
FEATRFC 2389Get the feature list implemented by the server
LANGRFC 2640Language negotiation
LISTReturns information of a file or directory if specified, else information of the current working directory is returned
LPRTRFC 1639Specifies a long address and port to which the server should connect
LPSVRFC 1639Enter long passive mode
MDTMRFC 3659Returns the last-modified time of a specified file
MICRFC 2228Integrity protected command
MKDRFC 959Make directory
MLSDRFC 3659List the contents of a directory if a directory is named
MLSTRFC 3659Provide data about exactly the object named on its command line, and no others
MODESet the transfer mode (Stream, Block, or Compressed)
NLSTReturn a list of file names in a specified directory
NOOPNo operation (dummy packet; used mostly on keepalives)
OPTSRFC 2389Select options for a feature
PASSAuthentication password
PASVEnter passive mode
PBSZRFC 2228Protection buffer size
PORTSpecifies an address and port to which the server should connect
PROTRFC 2228Data channel protection level
PWDRFC 959Print working directory. Returns the current directory of the host.
REINRe-initialize the connection
RESTRFC 3659Restart transfer from the specified point
RETRTransfer a copy of the file
RMDRFC 959Remove a directory
RNFRRename from
RNTORename to
SITESend site specific commands to remote server
SIZERFC 3659Return the size of a file
SMNTRFC 959Mount file structure
STATReturn the current status
STORAccept the data and store the data as a file at the server site
STOURFC 959Store file uniquely
STRUSet file transfer structure
SYSTRFC 959Return system type
TYPESet the transfer mode (ASCII/Binary)
USERAuthentication username
XCUPRFC 775Change to the parent of the current working directory
XMKDRFC 775Make a directory
XPWDRFC 775Print the current working directory
XRMDRFC 775Remove the directory
XSEMRFC 737Send, mail if cannot
XSENRFC 737Send to terminal

A short list of reply codes

  • 2xx - Success reply
  • 4xx or 5xx - Failure reply
  • 1xx or 3xx - Error or Incomplete reply

The second digit defines the kind of error:

  • x0z - Syntax - These replies refer to syntax errors.
  • x1z - Information - Replies to requests for information.
  • x2z - Connections - Replies referring to the control and data connections.
  • x3z - Authentication and accounting - Replies for the login process and accounting procedures.
  • x4z - Not defined.
  • x5z - File system - These replies relay status codes from the server file system.

By the way, the last FTP Technology is RCF 2428 since 1998. It's an unimportant information. Because it's about FTP's history. But we looked at the RCF 959 technology and it has been in use since 1985.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Team Leader
Turkey Turkey
No Biography provided

Comments and Discussions

QuestionHow To Programmaticaly C# Reset / Change FTP Password? Pin
Member 1370337110-Oct-20 2:24
MemberMember 1370337110-Oct-20 2:24 
AnswerRe: How To Programmaticaly C# Reset / Change FTP Password? Pin
OriginalGriff10-Oct-20 2:26
mveOriginalGriff10-Oct-20 2:26 
Questionhow to create a server and how to resolve the below error Pin
Member 124860163-Nov-16 4:56
MemberMember 124860163-Nov-16 4:56 
AnswerRe: how to create a server and how to resolve the below error Pin
SercanOzdemir15-Nov-16 3:31
MemberSercanOzdemir15-Nov-16 3:31 
AnswerFTP Help Pin
Member 1278856911-Oct-16 18:28
MemberMember 1278856911-Oct-16 18:28 
QuestionFTP Pin
Rajan Kumar3-Mar-15 19:25
MemberRajan Kumar3-Mar-15 19:25 
Question500 'MLSD': command not understood. Pin
joga778525-Jan-15 17:53
Memberjoga778525-Jan-15 17:53 
AnswerRe: 500 'MLSD': command not understood. Pin
SercanOzdemir26-Jan-15 0:37
MemberSercanOzdemir26-Jan-15 0:37 
GeneralRe: 500 'MLSD': command not understood. Pin
joga778526-Jan-15 5:30
Memberjoga778526-Jan-15 5:30 
BugRe: 500 'MLSD': command not understood. Pin
vishnu_patel18-Feb-15 19:38
Membervishnu_patel18-Feb-15 19:38 
GeneralRe: 500 'MLSD': command not understood. Pin
SercanOzdemir18-Feb-15 22:28
MemberSercanOzdemir18-Feb-15 22:28 
GeneralRe: 500 'MLSD': command not understood. Pin
vishnu_patel20-Feb-15 23:38
Membervishnu_patel20-Feb-15 23:38 
GeneralRe: 500 'MLSD': command not understood. Pin
SercanOzdemir20-Feb-15 23:43
MemberSercanOzdemir20-Feb-15 23:43 
GeneralRe: 500 'MLSD': command not understood. Pin
vishnu_patel20-Feb-15 23:50
Membervishnu_patel20-Feb-15 23:50 
GeneralRe: 500 'MLSD': command not understood. Pin
SercanOzdemir21-Feb-15 0:20
MemberSercanOzdemir21-Feb-15 0:20 
GeneralRe: 500 'MLSD': command not understood. Pin
vishnu_patel22-Feb-15 20:09
Membervishnu_patel22-Feb-15 20:09 
GeneralRe: 500 'MLSD': command not understood. Pin
SercanOzdemir22-Feb-15 20:30
MemberSercanOzdemir22-Feb-15 20:30 
GeneralRe: 500 'MLSD': command not understood. Pin
vishnu_patel22-Feb-15 22:50
Membervishnu_patel22-Feb-15 22:50 
GeneralRe: 500 'MLSD': command not understood. Pin
SercanOzdemir23-Feb-15 0:01
MemberSercanOzdemir23-Feb-15 0:01 
AnswerRe: 500 'MLSD': command not understood. Pin
vishnu_patel23-Feb-15 22:51
Membervishnu_patel23-Feb-15 22:51 
GeneralRe: 500 'MLSD': command not understood. Pin
SercanOzdemir23-Feb-15 22:56
MemberSercanOzdemir23-Feb-15 22:56 
GeneralRe: 500 'MLSD': command not understood. Pin
vishnu_patel23-Feb-15 23:04
Membervishnu_patel23-Feb-15 23:04 
Questiondoes not upload any file gives error Pin
fawadali1233-Dec-14 20:46
Memberfawadali1233-Dec-14 20:46 
AnswerRe: does not upload any file gives error Pin
SercanOzdemir10-Dec-14 19:25
MemberSercanOzdemir10-Dec-14 19:25 
QuestionGetListFiles() function not returning all the files and folders from server, it failed few times. Pin
Member 1057378324-Nov-14 23:18
MemberMember 1057378324-Nov-14 23:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.