Пример #1
0
 public void DownloadFiles(string server, string port, string user, string password,
                           string localPath, string remotePath, string archiveFilePath, string fileType,
                           bool recursive, bool archive)
 {
     try
     {
         InitClient(server, port, user, password);
         if (Connect())
         {
             foreach (var ftpListItem in ftp.GetListing(remotePath))
             {
                 RecursiveFiles(ftpListItem, fileType, localPath, remotePath, archiveFilePath, recursive, archive);
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Disconnect();
     }
 }
Пример #2
0
        /// <summary>
        /// 取得文件或目录列表
        /// </summary>
        /// <param name="remoteDic">远程目录</param>
        /// <param name="type">类型:file-文件,dic-目录</param>
        /// <returns></returns>
        public List <string> ListDirectory(string remoteDic, string type = "file")
        {
            List <string> list = new List <string>();

            type = type.ToLower();

            try
            {
                if (Connect())
                {
                    FtpListItem[] files = ftpClient.GetListing(remoteDic);
                    foreach (FtpListItem file in files)
                    {
                        if (type == "file")
                        {
                            if (file.Type == FtpFileSystemObjectType.File)
                            {
                                list.Add(file.Name);
                            }
                        }
                        else if (type == "dic")
                        {
                            if (file.Type == FtpFileSystemObjectType.Directory)
                            {
                                list.Add(file.Name);
                            }
                        }
                        else
                        {
                            list.Add(file.Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log4netUtil.Log4NetHelper.Error(String.Format(@"ListDirectory->取得文件或目录列表 异常:{0}", ex.Message), @"Ftp");
            }
            finally
            {
                DisConnect();
            }

            return(list);
        }
Пример #3
0
        public object[] list(object path)
        {
            connect();
            List <object> list = new List <object>();

            foreach (FtpListItem item in _client.GetListing(path.ToStringOrDefault()))
            {
                list.Add(
                    new JsObject
                {
                    { "name", item.Name },
                    { "fullName", item.FullName },
                    { "type", item.Type.ToStringOrDefault() },
                    { "modified", item.Modified },
                });
            }
            return(list.ToArray());
        }
Пример #4
0
        /// <summary>
        /// Transfer the specified directory from the source FTP Server onto the remote FTP Server using the FXP protocol.
        /// You will need to create a valid connection to your remote FTP Server before calling this method.
        /// In Update mode, we will only transfer missing files and preserve any extra files on the remote FTP Server. This is useful when you want to simply transfer missing files from an FTP directory.
        /// Currently Mirror mode is not implemented.
        /// Only transfers the files and folders matching all the rules provided, if any.
        /// All exceptions during transfer are caught, and the exception is stored in the related FtpResult object.
        /// </summary>
        /// <param name="sourceFolder">The full or relative path to the folder on the source FTP Server. If it does not exist, an empty result list is returned.</param>
        /// <param name="remoteClient">Valid FTP connection to the destination FTP Server</param>
        /// <param name="remoteFolder">The full or relative path to destination folder on the remote FTP Server</param>
        /// <param name="mode">Only Update mode is currently implemented</param>
        /// <param name="existsMode">If the file exists on disk, should we skip it, resume the download or restart the download?</param>
        /// <param name="verifyOptions">Sets if checksum verification is required for a successful download and what to do if it fails verification (See Remarks)</param>
        /// <param name="rules">Only files and folders that pass all these rules are downloaded, and the files that don't pass are skipped. In the Mirror mode, the files that fail the rules are also deleted from the local folder.</param>
        /// <param name="progress">Provide a callback to track download progress.</param>
        /// <remarks>
        /// If verification is enabled (All options other than <see cref="FtpVerify.None"/>) the hash will be checked against the server.  If the server does not support
        /// any hash algorithm, then verification is ignored.  If only <see cref="FtpVerify.OnlyChecksum"/> is set then the return of this method depends on both a successful
        /// upload &amp; verification.  Additionally, if any verify option is set and a retry is attempted then overwrite will automatically switch to true for subsequent attempts.
        /// If <see cref="FtpVerify.Throw"/> is set and <see cref="FtpError.Throw"/> is <i>not set</i>, then individual verification errors will not cause an exception
        /// to propagate from this method.
        /// </remarks>
        /// <returns>
        /// Returns a listing of all the remote files, indicating if they were downloaded, skipped or overwritten.
        /// Returns a blank list if nothing was transfered. Never returns null.
        /// </returns>
        public List <FtpResult> TransferDirectory(string sourceFolder, FtpClient remoteClient, string remoteFolder, FtpFolderSyncMode mode = FtpFolderSyncMode.Update,
                                                  FtpRemoteExists existsMode = FtpRemoteExists.Skip, FtpVerify verifyOptions = FtpVerify.None, List <FtpRule> rules = null, Action <FtpProgress> progress = null)
        {
            if (sourceFolder.IsBlank())
            {
                throw new ArgumentException("Required parameter is null or blank.", "sourceFolder");
            }

            if (remoteFolder.IsBlank())
            {
                throw new ArgumentException("Required parameter is null or blank.", "remoteFolder");
            }

            LogFunc(nameof(TransferDirectory), new object[] { sourceFolder, remoteClient, remoteFolder, mode, existsMode, verifyOptions, (rules.IsBlank() ? null : rules.Count + " rules") });

            var results = new List <FtpResult>();

            // cleanup the FTP paths
            sourceFolder = sourceFolder.GetFtpPath().EnsurePostfix("/");
            remoteFolder = remoteFolder.GetFtpPath().EnsurePostfix("/");

            // if the source dir does not exist, fail fast
            if (!DirectoryExists(sourceFolder))
            {
                return(results);
            }

            // flag to determine if existence checks are required
            var checkFileExistence = true;

            // ensure the remote dir exists
            if (!remoteClient.DirectoryExists(remoteFolder))
            {
                remoteClient.CreateDirectory(remoteFolder);
                checkFileExistence = false;
            }

            // collect paths of the files that should exist (lowercase for CI checks)
            var shouldExist = new Dictionary <string, bool>();

            // get all the folders in the local directory
            var dirListing = GetListing(sourceFolder, FtpListOption.Recursive).Where(x => x.Type == FtpFileSystemObjectType.Directory).Select(x => x.FullName).ToArray();

            // get all the already existing files
            var remoteListing = checkFileExistence ? remoteClient.GetListing(remoteFolder, FtpListOption.Recursive) : null;

            // loop thru each folder and ensure it exists
            var dirsToUpload = GetSubDirectoriesToTransfer(sourceFolder, remoteFolder, rules, results, dirListing);

            CreateSubDirectories(remoteClient, dirsToUpload);

            // get all the files in the local directory
            var fileListing = GetListing(sourceFolder, FtpListOption.Recursive).Where(x => x.Type == FtpFileSystemObjectType.File).Select(x => x.FullName).ToArray();

            // loop thru each file and transfer it
            var filesToUpload = GetFilesToTransfer(sourceFolder, remoteFolder, rules, results, shouldExist, fileListing);

            TransferServerFiles(filesToUpload, remoteClient, existsMode, verifyOptions, progress, remoteListing);

            // delete the extra remote files if in mirror mode and the directory was pre-existing
            // DeleteExtraServerFiles(mode, shouldExist, remoteListing);

            return(results);
        }
Пример #5
0
 /// <summary>
 /// Check if remote directory exists directory
 /// </summary>
 /// <param name="remotePath">Remote absolute path directory</param>
 /// <returns></returns>
 public bool DirectoryExists(string remotePath)
 {
     _FTPClient.GetListing("/");
     return(_FTPClient.DirectoryExists(remotePath));
 }
        public async Task <FtpClientResponse> ReadAsync(FtpConfig config, Func <string, Task <string> > securePasswordCallBack,
                                                        Func <string, string, string, MemoryStream, string, string, bool> copyFileFunc)
        {
            var response = new FtpClientResponse {
                ErrorMessage = FtpConstants.NoError, Status = FtpConstants.SuccessStatus, FileData = new List <FtpClientResponseFile>()
            };

            try
            {
                if (_ftpClient == null)
                {
                    await CreateFtpClientAsync(config, securePasswordCallBack);
                }
                else
                {
                    if (!_ftpClient.IsConnected)
                    {
                        await CreateFtpClientAsync(config, securePasswordCallBack);
                    }
                }

                var listOfFiles = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) => _ftpClient.GetListing(config.Ftp.Path).Where(f => f.Type == FtpFileSystemObjectType.File), new Polly.Context($"LIST_FILE_{config.Ftp.Path}"));

                //config.Ftp.ArchivedPath != config.Ftp.Path is delete mode
                if (!string.IsNullOrEmpty(config.Ftp.ArchivedPath) && config.Ftp.ArchivedPath != config.Ftp.Path)
                {
                    var folderExisted = _ftpClient.DirectoryExists(config.Ftp.ArchivedPath);
                    if (!folderExisted)
                    {
                        _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) => _ftpClient.CreateDirectory(config.Ftp.ArchivedPath), new Polly.Context("CREATE_ARCHIVE_FOLDER"));
                    }
                }

                var resolvedStorageAccountKey =
                    await securePasswordCallBack.Invoke(config.AzureBlobStorage.StorageKeyVault);

                Parallel.ForEach(
                    listOfFiles,
                    new ParallelOptions {
                    MaxDegreeOfParallelism = config.Parellelism
                },
                    item =>
                {
                    try
                    {
                        var fileName = item.Name;
                        using (var istream = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) => _ftpClient.OpenRead(item.FullName), new Polly.Context($"READ_FILE_{item.FullName}")))
                        {
                            bool isArchived           = false;
                            MemoryStream memoryStream = new MemoryStream();
                            istream.CopyTo(memoryStream);
                            memoryStream.Position = 0;
                            //_telemetryLogger.TrackTrace<FtpActor>("", "[ActorFtpClient] Reading File " + item.FullName, SeverityLevel.Information);
                            var copied = copyFileFunc.Invoke(config.AzureBlobStorage.ContainerName,
                                                             fileName,
                                                             config.Retry.StorageRetryPolicy, memoryStream, config.AzureBlobStorage.StorageAccountName, resolvedStorageAccountKey);

                            if (copied && !string.IsNullOrEmpty(config.Ftp.ArchivedPath) && config.Ftp.ArchivedPath != config.Ftp.Path)
                            {
                                isArchived = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) => _ftpClient.MoveFile(item.FullName, config.Ftp.ArchivedPath + "\\" + item.Name, FtpExists.Overwrite), new Polly.Context("COPY_FILE_TO_ARCHIVE"));
                            }
                            else if (config.Ftp.ArchivedPath == config.Ftp.Path)
                            {
                                //delete mode
                                isArchived = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) =>
                                {
                                    _ftpClient.DeleteFile(item.FullName);
                                    return(true);
                                }, new Polly.Context("DELETE_FILE_TO_ARCHIVE"));
                            }

                            var fres = new FtpClientResponseFile
                            {
                                Status       = (copied && isArchived) ? FtpConstants.SuccessStatus : FtpConstants.FailureStatus,
                                FileName     = item.Name,
                                ErrorMessage = (copied ? string.Empty : FtpConstants.BlobUploadError) + " " + (isArchived ? string.Empty : FtpConstants.ArchivedError)
                            };

                            var properties = new Dictionary <string, string> {
                                { "payload", JsonConvert.SerializeObject(fres) }
                            };
                            //_telemetryLogger.TrackEvent("", EventConstant.FtpCustomEventName, properties);
                            response.FileData.Add(fres);
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                    );

                //_telemetryLogger.TrackMetric("", EventConstant.FtpCustomEventName, 1);
                await Stop();
            }
            catch (FtpNotConnectException e)
            {
                response.ErrorMessage = response.ErrorMessage + e.Message;
                response.Status       = FtpConstants.FailureStatus;
            }
            catch (FtpSecurityNotAvailableException e)
            {
                response.ErrorMessage = response.ErrorMessage + e.Message;
                response.Status       = FtpConstants.FailureStatus;
            }
            catch (Exception e)
            {
                response.ErrorMessage = response.ErrorMessage + e.Message;
                response.Status       = FtpConstants.FailureStatus;
            }
            return(response);
        }
Пример #7
0
        public async Task <FtpClientResponse> ReadAsync(FtpConfig config, Func <string, Task <string> > securePasswordCallBack,
                                                        Func <string, string, string, MemoryStream, string, string, bool> copyFileFunc)
        {
            var response = new FtpClientResponse {
                ErrorMessage = FtpConstants.NoError, Status = FtpConstants.SuccessStatus, FileData = new List <FtpClientResponseFile>()
            };

            try
            {
                await CreateFtpClientAsync(config, securePasswordCallBack);

                Func <FtpListItem, bool> predicate = f => f.Type == FtpFileSystemObjectType.File;
                if (!string.IsNullOrEmpty(config.Ftp.FilenameRegex))
                {
                    var rx = new Regex(config.Ftp.FilenameRegex, RegexOptions.IgnoreCase);
                    predicate = f => f.Type == FtpFileSystemObjectType.File && rx.IsMatch(f.Name);
                }

                var listOfFiles = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy)
                                  .Execute((context) => _ftpClient.GetListing(config.Ftp.Path).Where(predicate), new Polly.Context($"LIST_FILE_{config.Ftp.Path}"));

                if (!string.IsNullOrEmpty(config.Ftp.ArchivedPath) && config.Ftp.ArchivedPath != config.Ftp.Path)
                {
                    var folderExisted = _ftpClient.DirectoryExists(config.Ftp.ArchivedPath);
                    if (!folderExisted)
                    {
                        _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) => _ftpClient.CreateDirectory(config.Ftp.ArchivedPath), new Polly.Context("CREATE_ARCHIVE_FOLDER"));
                    }
                }

                var resolvedStorageAccountKey =
                    await securePasswordCallBack.Invoke(config.AzureBlobStorage.StorageKeyVault);

                foreach (var item in listOfFiles)
                {
                    bool copied     = false;
                    bool isArchived = false;
                    try
                    {
                        var fileName = item.Name;
                        using (var istream = await _ftpClient.OpenReadAsync(item.FullName))
                        {
                            MemoryStream memoryStream = new MemoryStream();
                            istream.CopyTo(memoryStream);
                            memoryStream.Position = 0;
                            copied = copyFileFunc.Invoke(config.AzureBlobStorage.ContainerName,
                                                         fileName,
                                                         config.Retry.StorageRetryPolicy, memoryStream, config.AzureBlobStorage.StorageAccountName, resolvedStorageAccountKey);
                        }
                        if (copied && !string.IsNullOrEmpty(config.Ftp.ArchivedPath) && config.Ftp.ArchivedPath != config.Ftp.Path)
                        {
                            isArchived = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) => _ftpClient.MoveFile(item.FullName, config.Ftp.ArchivedPath + "\\" + item.Name, FtpExists.Overwrite), new Polly.Context("COPY_FILE_TO_ARCHIVE"));
                        }
                        else if (config.Ftp.ArchivedPath == config.Ftp.Path)
                        {
                            //delete mode
                            isArchived = _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpCommandPolicy).Execute((context) =>
                            {
                                _ftpClient.DeleteFile(item.FullName);
                                return(true);
                            }, new Polly.Context("DELETE_FILE_TO_ARCHIVE"));
                        }

                        var fres = new FtpClientResponseFile
                        {
                            Status       = (copied && isArchived) ? FtpConstants.SuccessStatus : FtpConstants.FailureStatus,
                            FileName     = item.Name,
                            ErrorMessage = (copied ? string.Empty : FtpConstants.BlobUploadError) + " " + (isArchived ? string.Empty : FtpConstants.ArchivedError)
                        };
                        response.FileData.Add(fres);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"ActorFtpClient failed to process the file {item.Name}, copy: {copied}, archived {isArchived}. Error: {ex.Message}");
                    }
                }
                await Stop();
            }
            catch (Exception e)
            {
                response.ErrorMessage = response.ErrorMessage + e.Message;
                response.Status       = FtpConstants.FailureStatus;
                _logger.LogError(e, $"ActorFtpClient failed to start creating the client of {config.Ftp.Host} : {e.Message}");
            }
            return(response);
        }