C # compile FTP client software

Source: Internet
Author: User

1 Introduction

I know. There are many ready-made FTP software on the Internet. However. We also want to know some underlying FTP institutions. This open-source project may be helpful to you when you learn FTP knowledge.ProgramThe interface looks like filezilla. Although filezilla is popular, it has some bugs. When I open my blog, there is always a problem. I need to connect to my server through FTP. Send and download files. Because. I decided to write my own software to handle all the situations. Filezilla is good enough. But it is not mine.

 

2 Background

 

Let's see what we already know. We know that FTP is a standard TCP-based network protocol. Transfers files from one host to another. It is a C/S architecture.

 

Figure 2

 

FTP programs were once Based on command lines. We can still connect to the FTP server through cmd.exe. Because FTP can indeed be operated through commands. For example. We can use the "stor" command on the command line to send files. To complete these requests. The FTP server must always run and wait for client requests to come. We can better understand FTP from Wikipedia:

 

The client computer can communicate with the server through port 21 of the server. It is called a control connection. It remains open during a session. The first connection. A data connection is called a data connection. The server can open port 20 (active mode) to the client, establish a data path, and connect to the client to transmit data. Or the client opens a random port (passive mode) to connect to the server to transmit data. The control connection uses a telnet-like Protocol and is used for client and server session management (commands, identifiers, and passwords ).. For example. "RetrFilename"The file will be downloaded from the server.

Figure 3

Two types of connections are required for a complete FTP file transfer. One is a file transfer command called a control connection, and the other is a real file transfer called a data connection.

The server sends a response to the control connection through a three-digit ASCII status code that may contain optional descriptions. For example. "200" or "200 OK" indicates that the previous command was successful. Numbers represent numbers. The description provides instructions (such as "OK"), or some required parameters (such as the need for an account to store files). What should we do. Obviously. Send commands, receive "OK" responses, and send data. Receive data. Finished. But first, the server is ready. The FTP server can run in active and passive modes. The active mode is server-based connection, while the passive mode is the connection of the client. Continue.

In active connection, the client sends its own IP address and port to the server. Then the server tries to connect to the client, but may be rejected for firewall reasons. We use anti-virus/built-in firewall on Windows. Right. Let's look at the passive mode.

In a passive connection. The server sends its IP address and port to the client through a "PASV" command. Then the client tries to connect to the server through this IP address. It is very useful for sending files. When we send a file. The "PASV" mode is preferred, as you said. Most protocols. For example, FTP/HTTP uses ASCII encoding because it is globally available. So we will use this encoding. You can get the FTP command list from below

Both active and passive are for the server.

3. Use Code

Now we are ready for writing software. Let's write some useful code. :) First. The "Open File Dialog Box" is integrated into our form.

3.1 Resource Manager Components

We need a Resource Manager component to view all our files on the software interface. In this way, we can select the files to be sent to the FTP server and create a Windows form control library (provided in the download package)

Figure 4

It looks like the above. First add a Treeview, some buttons, and a search function

 
Treeview. nodes. Clear (); treenode noded=NewTreenode (); noded. Tag=Environment. getfolderpath (environment. specialfolder. desktop); noded. Text="Desktop"; Noded. imageindex=10; Noded. selectedimageindex=10; Treeview. nodes. Add (noded );

As shown in the code above. We need to add a master node. My documents. My computer and so on. Then obtain the subdirectory.

 String  [] Dirlist; dirlist = Directory. getdirectories (parentnode. Tag. tostring (); array. Sort (dirlist );  If (Dirlist. Length = Parentnode. nodes. Count)  Return  ;  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  ; Parentnode. nodes. Add (node );} 

 

You can see the complete code from the downloaded package. We should also handle the mouse click event.

Now we have a resource manager. And all the information required by FTP and.

First, we 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); ftpsocket. Connect (addrendpoint ); 

 

 
Yes. We need a socket to connect to the server and then send the command
Appendtext (rchlog,"Command:"+ MSG +"\ N", Color. Blue); byte [] commandbytes= Encoding. ASCII. getbytes (MSG +"\ R \ n"). Tochararray (); ftpsocket. Send (commandbytes, commandbytes. length,0);//Read responseReadresponse ();

We send commands to the server. The server responds in its own language. We need to understand him. The response includes three digits and some explanations.

 

 Private   String Splitresponse (){  Try  {  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                  Break  ;}  String [] MSG = statusmessage. Split ( '  \ N  '  );  If (Statusmessage. length> 2  ) Statusmessage = MSG [MSG. Length- 2 ]; // Remove last \ n          Else  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); ftpsocket. Close ();  Return   ""  ;}} 

 

Finished. Now we can download, upload, and rename. Or deleted.

4. FTP command list
Command Description
Abor Interrupts the transmission of an active file.
Acct System Account Information
Adat Authentication/security data
Allo Allocate space to receive files
Appe Add files to the server
Auth Authentication/Security Mechanism
CCC Clear command channel
Cdup Go to parent directory
Conf Confidentiality Protection Command
CWD Change the working directory on the server
Dele Deletes a specified file on the server.
ENC Confidential protection channel
Eprt Specify the extended address and port that a server should connect
Epsv Enter the extended Passive Mode
Feat Obtain the function list provided by the server.
Help Returns the specified command information.
Lang Returned Language Information
List If the file name is used to list file information, if the file name is a directory, the file list is listed.
Lprt Specify the long address and port that a server should connect
Lpsv Enter long Passive Mode
MDTM Returns the last file modification time.
Mic Complete protection commands
MKD Create directory
MLSD Lists the contents of a specified directory.
Mlst List precise object information on the command line
Mode Transmission Mode (S = stream mode, B = block mode, c = compression mode)
NLST List contents of a specified directory
Noop No action, (Virtual package, from frequent connection)
Opts Select a feature Option
Pass Verify Password
PASV Enter passive mode
Pbsz Protection buffer size
Port Specify the address and port that the server should connect
Prot Data Channel Protection Level
PWD Display current working directory
Quit Log out from the FTP server
Rein Reinitialize the logon status connection
Rest Restart the file at a specified point for transfer
RETR Transfer file copies
RMD Delete a specified directory on the server
RNFR Rename from old name
RNTO To new name
Site Send the specified command to the remote server
Size Returned File Size
SMNT Mount the specified file structure
Stat Returns the current status.
Stor Store (copy) the file to the server
STOU Store files to specified files on the server
Stru Set the structure (F = file, r = record, P = page)
Syst Back to the operating system used by the server
Type Transmission Mode (A = ASCII, E = ebcdic, I = binary)
User Verify user
Xcup Jump to the parent directory of the current working path
Xmkd Create directory
Xpwd Output current working directory
Xrmd Delete directory

 

5. Return code list
    • 2XX-success returned
    • 4xx or 5xx-return failure
    • 1xx or 3xx-incorrect or incomplete reply

The second field defines the error type.

    • X0z-syntax error.
    • X1z-information-Request Information
    • X2z-connection-indicates a problem with the control or data connection
    • X3z-account authentication-Logon or account authentication problems.
    • X4z-undefined
    • X5z-file system-it may be a problem with the Server File System.

 

Download demo

C # compile an FTP Client

6. License

This article includesSource codeAnd file authorization under cpol.

 

Original article address: file-transfer-Protocol-ftp-Client

Copyright statement: This article by http://leaver.me translation, welcome to repost share. Please respect the work of the author. Keep this note and the author's blog link when reprinting. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.