A simple FTP application Zhuan in. NET 2.0 (C #)

Source: Internet
Author: User
Tags ftp client

Address: http://www.c-sharpcorner.com/UploadFile/neo_matrix/SimpleFTP01172007082222AM/SimpleFTP.aspx
[Source code download]

 

. NET 2.0 (C #) Simple FTP applicationProgram

Original article released on: 2007.01.18
Author: Neo Matrix
Translation: webabcd

This article uses. NET 2.0 (C #) to implement general FTP functions.

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 sectionCodeThere is no 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. In this articleArticleWill show you the simple code for implementing FTP under. NET 2.0. The language 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-specify 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 FTP servers, 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 happens during upload)
· method-specifies the current request command (upload, download, filelist, etc ). 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 );

Reqftp = (ftpwebrequest) ftpwebrequest. Create (New uri ("ftp: //" + ftpserverip + "/" + filename ));

Reqftp. method = webrequestmethods. FTP. downloadfile;

Reqftp. usebinary = true;

Reqftp. Credentials = new networkcredential (ftpuserid, ftppassword );

Ftpwebresponse response = (ftpwebresponse) reqftp. getresponse ();

Stream ftpstream = response. getresponsestream ();

Long Cl = response. contentlength;

Int buffer size = 2048;

Int readcount;

Byte [] buffer = new byte [buffersize];

Readcount = ftpstream. Read (buffer, 0, buffersize );

While (readcount> 0)
{
Outputstream. Write (buffer, 0, readcount );

Readcount = ftpstream. Read (buffer, 0, buffersize );
}

Ftpstream. Close ();

Outputstream. Close ();

Response. Close ();
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}
The above code implements the file download function from the FTP server. This is different from the previously mentioned upload function. A response stream is required for download, which contains the content of the downloaded file. The downloaded file is specified by the URI in the ftpwebrequest object. After obtaining the requested file, use the getresponse () method of the ftpwebrequest object to download the file. It downloads the file as a stream to your client machine.

Note: We can set the storage path and name of the file on our local machine.

Public String [] getfilelist ()
{
String [] downloadfiles;
Stringbuilder result = new stringbuilder ();
Ftpwebrequest reqftp;
Try
{
Reqftp = (ftpwebrequest) ftpwebrequest. Create (New uri ("ftp: //" + ftpserverip + "/"));
Reqftp. usebinary = true;
Reqftp. Credentials = new networkcredential (ftpuserid, ftppassword );
Reqftp. method = webrequestmethods. FTP. listdirectory;
Webresponse response = reqftp. getresponse ();
Streamreader reader = new streamreader (response. getresponsestream ());
String line = reader. Readline ();
While (line! = NULL)
{
Result. append (line );
Result. append ("\ n ");
Line = reader. Readline ();
}
// To remove the trailing '\ N'
Result. Remove (result. tostring (). lastindexof ('\ n'), 1 );
Reader. Close ();
Response. Close ();
Return result. tostring (). Split ('\ n ');
}
Catch (exception ex)
{
System. Windows. Forms. MessageBox. Show (ex. Message );
Downloadfiles = NULL;
Return downloadfiles;
}
}
The code above demonstrates how to obtain the file list from the FTP server. Uri points to the address of the FTP server. We use a streamreader object to store a stream. The file name list is separated by "\ r \ n", that is, each file name occupies one row. You can use the readtoend () method of the streamreader object to obtain the file list. In the code above, we use a stringbuilder object to save the file name, and then separate the results using separators and return the results as an array. I'm sure it's just a good method.

Other implementations, such as rename, delete, getfilesize, filelistdetails, and makedir, are similar to the above Code.

Note: to implement the rename function, set the new name to the renameto attribute of the ftpwebrequest object. When connecting to a specified directory, you must specify it in the URI used by the ftpwebrequest object.

Notes
Pay attention to the following points when coding:
· Unless the enablessl attribute is set to true, no data is made, and your username and password are sent to the server in plain text, anyone who monitors the network can obtain verification information about your connection to the server. If the FTP server you connect to provides SSL, you should set the enablessl attribute to true.
· If you do not have the permission to access the FTP server, a securityexception error will be thrown.
· To send a request to the FTP server, call the getresponse method. After the requested operation is complete, an ftpwebresponse object will be returned. This ftpwebresponse object provides the operation status and data that has been downloaded from the FTP server. The statuscode attribute of the ftpwebresponse object provides the final status code returned by the FTP server. The statusdescription attribute of the ftpwebresponse object is the description of the status code.

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.