Simple FTP application under. NET 2.0 (C #)

Source: Internet
Author: User
Tags file size ftp implement connect readline requires tostring ftp client
Program

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


Introduced
Microsoft's. NET Framework 2.0 has increased support for FTP relative to 1.x. In the past, in order to meet my needs, I did not use a Third-party class library to achieve FTP functionality, but for the sake of reliability, it is better to use the. NET Framework analogy. My Code does not form a reusable class library, but it is easier to understand and meets your needs. It can upload, download, delete and other arbitrary functions. At the end of this article we will show you the simple code for FTP under. NET 2.0, which is in C #. Perhaps because this is the. NET new class, or the third party class library has been able to achieve your needs, the. NET 2.0 of this part of the class library has not received enough attention.


Background
As part of my work, I have used the FTP module, but I can only use it in. NET 1.1, so I can't delve into the implementation of. NET 2.0 FTP. But I believe that the support for FTP under NE 2.0 is very good.


Code
Don't forget to introduce namespaces
Using System.Net;
Using System.IO;
The following steps include a general procedure for using the FtpWebRequest class to implement FTP functionality

1, create a FtpWebRequest object, point to the FTP server URI
2, set the FTP implementation method (upload, download, etc.)
3. Set properties for FtpWebRequest objects (whether SSL is supported, binary transmissions are used, etc.)
4, Set login authentication (username, password)
5, the implementation of the request
6, receive the corresponding flow (if necessary)
7, if there is no open stream, then close the FTP request

The development of any FTP application requires a related FTP server and its configuration information. FtpWebRequest exposes some properties to set this information.

The next code example is the upload function

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

Then set the properties of the FtpWebRequest object according to the FTP request

Some of the important properties are as follows:
    Credentials-Specifies the user name and password to log on to the FTP server.
    KeepAlive-Specifies whether the connection should be closed or closed after the request completes, and the default is True
    Usebinary-Specifies the type of file transfer. There are two types of file transfer modes, one is binary, and the other is ASCII. The 8th bit of the byte is different when the two methods are transferred. ASCII uses the 8th bit as error control, and the 8-bit binary is meaningful. So be careful when you use ASCII to transmit. Simply put, if you can read and write files in Notepad with ASCII transmission is safe, while others must use the binary mode. Of course, using binary mode to send ASCII files is also very good.
    Usepassive-Specifies whether active or passive mode is used. All previous clients used active mode and worked well, and now because of the presence of the client firewall, some ports will be closed so that the active mode will fail. In this case, passive mode is used, but some ports may also be blocked by the server's firewall. However, because the FTP server needs its FTP service to connect to a certain number of clients, they always support passive mode. This is why we use passive mode, in order to ensure that the data can be transmitted correctly, using passive mode is significantly better than active mode. (Translator Note: The active (port) mode establishes the data transmission channel is initiates by the server side, the server uses 20 ports to connect the client's one more than 1024 port; in the passive (PASV) mode, the data transmission channel is established by the FTP client, He uses a port greater than 1024 to connect to more than 1024 of the server's port)
    ContentLength-Setting this property is useful for the FTP server, but the client does not use it because FtpWebRequest ignores this property, so in this case the property is invalid. But if we set this property, the FTP server will anticipate the size of the file in advance (this happens when upload)
    Method-Specifies what command the current request is (upload,download,filelist, etc.). This value is defined in the webrequestmethods.ftp of the struct body.

private void Upload (string filename)
{
FileInfo Fileinf = new FileInfo (filename);
String uri = "ftp://" + Ftpserverip + "/" + fileinf.name;
FtpWebRequest reqftp;

Create a FtpWebRequest object from a URI
Reqftp = (ftpwebrequest) ftpwebrequest.create (New Uri ("ftp://" + Ftpserverip + "/" + Fileinf.name));

FTP User name and password
Reqftp.credentials = new NetworkCredential (Ftpuserid, FTPPassword);

The default is true, the connection is not closed
To be executed after a command
Reqftp.keepalive = false;

Specify what command to perform
Reqftp.method = WebRequestMethods.Ftp.UploadFile;

Specify data Transfer Type
Reqftp.usebinary = true;

Notifies the server of file size when uploading files
Reqftp.contentlength = Fileinf.length;

Buffer size set to 2KB
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 for each read file stream
Contentlen = fs. Read (Buff, 0, bufflength);

Stream content does not end
while (Contentlen!= 0)
{
Writes content from file stream to upload stream
Strm. Write (Buff, 0, Contentlen);

Contentlen = fs. Read (Buff, 0, bufflength);
}

Turn off 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 a FtpWebRequest object that points to an FTP server, and then set its different property credentials,keepalive,method,usebinary,contentlength.

Open the file on the local machine and write its contents to the FTP request stream. The size of the buffer is 2KB, whether uploading large files or small files, this is a suitable size.

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 buffersize = 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 code above implements the ability to download files from an FTP server. This is different from the previous upload function, the download requires a response stream, it contains the contents of the download file. This downloaded file is specified in the URI of the FtpWebRequest object. After the requested file is obtained, the file is downloaded through the FtpWebRequest object's GetResponse () method. It will take the file as a stream down to your client's 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 above code example demonstrates how to obtain a list of files from an FTP server. The URI points to the address of the FTP server. We use the StreamReader object to store a stream, and the file name list is separated by "\ r \ n", which means that each file name occupies one row. You can use the StreamReader object's ReadToEnd () method to get a list of files. In the code above we use a StringBuilder object to save the file name and then return the result as an array, separated by a delimiter. I'm sure it's just a better way.

Other implementations, such as Rename,delete,getfilesize,filelistdetails,makedir, are similar to the preceding code, and are not much more than that.

Note: When you implement the renaming function, you set the new name to the Renameto property of the FtpWebRequest object. When connecting to a specified directory, it needs to be specified in the URI used by the FtpWebRequest object.


where you need attention.
You need to keep the following points in mind when coding:
• Unless the Enablessl property is set to True, all data, including your username and password, will be sent to the server, and anyone who monitors the network can obtain authentication information about your connection to the server. If you are connecting to an FTP server that provides SSL, you should set the Enablessl property to True.
• If you do not have access to the FTP server, a SecurityException error will be thrown
• Sending requests to the FTP server requires calling the GetResponse method. When the requested operation completes, a FtpWebResponse object is returned. This FtpWebResponse object provides the state of the operation and data that has been downloaded from the FTP server. The StatusCode property of the FtpWebResponse object provides the final status code returned by the FTP server. The Statusdescription property of the FtpWebResponse object is a description of this state 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.