Fluent FTP, a useful FTP framework under. Net core

Time:2021-10-18

Projects often involve uploading files to other spaces or servers in batches. At this time, we may need to use FTP protocol for transmission, so I recommend fluent FTP, a very useful FTP transmission framework.

GitHub address:https://github.com/robinrodricks/FluentFTP

Nuget installation:

PM> Install-Package FluentFTP

First, create a new client:

1 /*
 2 the first parameter is the FTP address. Note that the protocol name should be added
 3 the second parameter is port, which is 21 by default
 4 the third parameter is the FTP user name
 5 the fourth parameter is the FTP password
 6 under normal conditions, three attributes can be configured, and you can select as needed:
 7 encryptionmode specifies the encryption method. Here, I choose none not to encrypt,
 8 dataconnectiontype refers to the connection mode. Generally, PASV passive mode or port active mode is selected, which can be modified according to the situation of ftpserver
 9 encoding is the specified encoding
10 */
11 var ftpClient = new FtpClient($"ftp://{host}", port, userName, passWord)
12 {
13     EncryptionMode = FtpEncryptionMode.None,
14     DataConnectionType = FtpDataConnectionType.PASV,
15     Encoding = Encoding.UTF8
16 };

Next, step 2: log in to FTP:

1 // isconnected determines whether the client has established a connection with the remote service
 2 if (!ftpClient.IsConnected)
 3 {
 4 // initiate connection login
 5     await ftpClient.ConnectAsync();
 6 // enable utf8 transmission
 7     var result = ftpClient.Execute("OPTS UTF8 ON");
 8     if (!result.Code.Equals("200") && !result.Code.Equals("202"))
 9         ftpClient.Encoding = Encoding.GetEncoding("ISO-8859-1");
10 }

  There is a pit here, especially for partners who don’t know FTP, and even tangle for a long time, that isIf the file name is Chinese, the file name will become garbled after uploading。 The reason is that some ftpservers do not enable utf8 encoded transmission or even support utf8 encoded transmission by default. At this time, we need to manually enable it. The FTP command is opts utf8 on

ftpClient.Execute("OPTS UTF8 ON");

At this time, ftpserver will return a status code, 200 indicates successful startup; 202 is always enabled, which means that the ftpserver will always be in the state of enabling UTF-8 coding, and there is no need to start it manually.

In addition, as mentioned earlier, ftpserver does not support utf8 encoded transmission. At this time, we need to set the previous encoding to iso-8859-1:

ftpClient.Encoding = Encoding.GetEncoding("ISO-8859-1");

Step 3: upload files:

1 /// 
 2 // upload a single file
 3 /// 
 4 // file source path
 5 // upload to the specified FTP folder path
 6 public async void UploadFile(string sourcePath, string destPath)
 7 {
 8      if (!File.Exists(sourcePath))
 9          return;
10      var fileInfo = new FileInfo(sourcePath);
11      await ftpClient.UploadFileAsync(sourcePath, $"{destPath}/{fileInfo.Name}", createRemoteDir: true);
12 }

If you want to upload files in batches, you can directly upload the entire folder by using ftpclient. Uploaddirectoryasync().

        There is a pit here. If there are too many files in the ftpserver directory(Note: not the number of files you uploaded), uploading takes a long time. After I checked the ftpserver log, I found that,When using uploaddirectoryasync(), fluent FTP will first get the list of all files and folders, it is a waste of time to start uploading after obtaining all the list information. After trying to solve the problem, I went to GitHub to find it. The author’s reply is:

  Currently we support 2 modes, update and mirror. In any mode, the remote directory is fully listed, then compared, then the actually upload begins. This is done in order to skip files that are already uploaded. We can support a third mode, maybe like BlindTransfer which will not list the remote directory.

At present, we support two modes: update and image. In any mode, the remote directory is fully listed, compared, and then the actual upload begins. This is done to skip files that have already been uploaded. We can support a third mode, such as blindtransfer, which does not list remote directories.

However, under the latest version 33.0.3, only mirror and update modes are still supported.

  Issues:https://github.com/robinrodricks/FluentFTP/issues/616

Therefore, if batch upload is required, you can make another layer of packaging on the basis of single file upload. As for other functions such as downloading, deleting and viewing, no other pits have been found yet. Net core 3.1.

Here are some common methods. The rest will not be repeated here. Just look at the notes of the document and framework:

//Download File
ftpClient.DownloadFileAsync();
//Download File夹
ftpClient.DownloadDirectoryAsync();
//Delete file
ftpClient.DeleteFileAsync();
//Delete file夹
ftpClient.DeleteDirectoryAsync();
//Determine whether the file exists
ftpClient.FileExistsAsync();
//Determine whether the folder exists
ftpClient.DirectoryExistsAsync();
//Get list details
ftpClient.GetListingAsync();

Finally, remember to log out and release resources:

1 if (ftpClient.IsConnected)
2 {
3 // off
4     await ftpClient.DisconnectAsync();
5     ftpClient.Dispose();
6 }

In addition to the above pits, fluent FTP is very complete and powerful. It provides a variety of methods and configurations. It is recommended that you use it.

   author:https://www.cnblogs.com/abnerwong/