. Net 2.0 (c #) Simple FTP application

Source: Internet
Author: User
Tags ftp client

Introduction
Compared with 1.x, Microsoft's. net framework 2.0 adds FTP support. In the past, in order to meet my needs, I did not want to use third-party class libraries to implement FTP functions. However, for reliability, it is better to use. net framework classes. My code is not made into a reusable class library, but it is easy to understand and can meet your needs. It can be used to upload, download, delete, and other functions. Later in this article, we will show you the simple code for implementing ftp in. net 2.0. The language used is c #. It may be because this is a new class added by. net, or a third-party class library can meet your needs well. This category library of. net 2.0 has not received enough attention.


Background
As part of my work, I have already used the ftp module, but I can only use it in. net 1.1, so I cannot thoroughly study the ftp implementation under. net 2.0. However, I believe that ftp support in. ne 2.0 is very good.


Code
Do not forget to introduce the namespace
Using System. Net;
Using System. IO;
The following steps include the general process of using the FtpWebRequest class to implement ftp Functions

1. Create an FtpWebRequest object pointing to the ftp server uri
2. Set the ftp execution method (upload, download, etc)
3. Set attributes for the FtpWebRequest object (whether to support ssl or binary transmission)
4. Set logon authentication (user name and password)
5. execute the request
6. Receive the corresponding stream (if needed)
7. If no stream is opened, disable the ftp request.

Developing any ftp application requires a related ftp server and its configuration information. FtpWebRequest exposes some attributes to set this information.

The following code demonstrates the upload function.

First, set a uri address, including the path and file name. This uri is used in the FtpWebRequest instance.

Set the FtpWebRequest Object Attributes Based on the ftp request.

Some important attributes are as follows:
· Credentials-specifies the username and password used to log on to the ftp server.
· KeepAlive-specifies whether the connection should be closed or closed after the request is completed. The default value is true.
· UseBinary-specifies the file transfer type. There are two file transmission modes: Binary and ASCII. When the two methods are used for transmission, the 8th-bit bytes are different. ASCII uses 8th bits as error control, while Binary's 8 bits make sense. So be careful when using ASCII transmission. To put it simply, it is safe to transmit files that can be read and written using notepad in ASCII mode, while others must use Binary mode. Of course, it is also very good to use Binary mode to send ASCII files.
· UsePassive-specifies whether the active or passive mode is used. Early on, all clients used active mode and work well. Now, some ports will be closed because of the existence of the Client Firewall, so that the active mode will fail. In this case, the passive mode is required, but some ports may also be blocked by the server's firewall. However, because the ftp server requires its ftp service to connect to a certain number of clients, they always support the passive mode. This is why we need to use the original intent of the passive mode. To ensure that data can be transmitted correctly, the passive mode is obviously better than the active mode. (Note: In active (PORT) mode, a data transmission channel is initiated by the server. The server uses PORT 20 to connect to a PORT greater than 1024 of the client. In passive (PASV) in this mode, the establishment of the data transmission channel is initiated by the FTP client, which uses a port greater than 1024 to connect to a port greater than 1024 of the server)
· ContentLength-setting this attribute is useful for the ftp server, but is not used by the client. Because FtpWebRequest ignores this attribute, this attribute is invalid in this case. However, if this attribute is set, the ftp server will predict the file size in advance (this will happen during upload)
· Method-specifies the command (upload, download, filelist, etc.) for the current request ). This value is defined in the struct WebRequestMethods. Ftp.

Private void Upload (string filename)
{
FileInfo fileInf = new FileInfo (filename );
String uri = "ftp: //" + ftpServerIP + "/" + fileInf. Name;
FtpWebRequest reqFTP;

// Create an FtpWebRequest object based on the uri
ReqFTP = (FtpWebRequest) FtpWebRequest. Create (new Uri ("ftp: //" + ftpServerIP + "/" + fileInf. Name ));

// Ftp user name and password
ReqFTP. Credentials = new NetworkCredential (ftpUserID, ftpPassword );

// The default value is true, and the connection will not be closed
// Executed after a command
ReqFTP. KeepAlive = false;

// Specify the command to be executed
ReqFTP. Method = WebRequestMethods. Ftp. UploadFile;

// Specify the data transmission type
ReqFTP. UseBinary = true;

// Notify the server of the file size when uploading the file
ReqFTP. ContentLength = fileInf. Length;

// Set the buffer size to 2 kb.
Int buffLength = 2048;

Byte [] buff = new byte [buffLength];
Int contentLen;

// Open a file stream (System. IO. FileStream) to read the uploaded file
FileStream fs = fileInf. OpenRead ();
Try
{
// Write the uploaded file to the stream
Stream strm = reqFTP. GetRequestStream ();

// 2kb of each file stream read
ContentLen = fs. Read (buff, 0, buffLength );

// The stream content has not ended
While (contentLen! = 0)
{
// Write content from file stream to upload stream
Strm. Write (buff, 0, contentLen );

ContentLen = fs. Read (buff, 0, buffLength );
}

// Close two streams
Strm. Close ();
Fs. Close ();
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message, "Upload Error ");
}
}

The above code is a simple example of the ftp upload function. Create an FtpWebRequest object pointing to an ftp server, and set its different attributes Credentials, KeepAlive, Method, UseBinary, and ContentLength.

Open a file on the local machine and write its content to the ftp request stream. The buffer size is 2 kb. This is a suitable size for uploading large or small files.

 


 

Private void Download (string filePath, string fileName)
{
FtpWebRequest reqFTP;

Try
{
FileStream outputStream = new FileStream (filePath + "\" + fileName, FileMode. Create );

ReqF

Related Article

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.