카테고리 없음

[C#] ftp download files

Victory_HA 2025. 4. 25. 09:17
public bool DownloadFilesRecursive(FtpTransfer ftp, string localDirectory, string remoteFileFullPath)
{
    try
    {
        var files = GetFilesInRemote(ftp, remoteFileFullPath);

        foreach (var file in files)
        {
            var remoteFilePath = Path.Combine(remoteFileFullPath, file);
            var localFilePath = Path.Combine(localDirectory, file);

            if (ftp.DirectoryExists(remoteFilePath))
            {
                Directory.CreateDirectory(localFilePath);
                DownloadFilesRecursive(ftp, localFilePath, remoteFilePath);
            }
            else if (!ftp.FileExists(localFilePath))
            {
                ftp.DownloadFile(localFilePath, remoteFilePath);
            }
            else
            {
                _logger.Info($"Already had files, skipping download: {localFilePath}");
            }
        }
    }
    catch (Exception ex)
    {
        _logger.Error($"Failed to download the files" +
            $", ex={ex}");
        return false;
    }
    return true;
}

 private List<string> GetFilesInRemote(FtpTransfer ftp, string remotePath)
 {
     if (!ftp.IsConnected && !FtpConnection(ftp))
     {
         return new List<string>();
     }

     var files = GetFtpFolderList(ftp, remotePath);
     if (files == null)
     {
         _logger.Error("There is no path in the FTP server folder");
         return new List<string>();
     }

     if (files.Count <= 0)
     {
         _logger.Error("There are no files in the FTP server folder");
         return new List<string>();
     }

     return files;
 }

public List<string> GetFtpFolderList(FtpTransfer ftp, string localPath)
{
    var isExistDirectoryInRemote = ftp.DirectoryExists(localPath);
    if (!isExistDirectoryInRemote)
    {
        return null;
    }

    var files = ftp.GetFileList(localPath);
    return files.Select(file => file.Name).ToList();
}