Список каталогов с около 2 000 000 файлов по протоколу FTP

У меня есть каталог с около 2 000 000 файлов на FTP-сервере. Этот FTP-сервер основан на Linux. Я хочу перечислить файлы в этом каталоге (имя файла с датой последнего изменения), но ни Filezilla, ни Core FTP Pro не могут это сделать, и операция со списком не будет выполнена. Я пытался написать свое собственное приложение на C#, используя класс FTPWebRequest, и запустил метод ListDirectory, но он также не может перечислить файлы в каталоге, и время ftpwebrequest истекло.
Есть ли способ перечислить имена файлов в каталоге с использованием любого протокола (например, FTP, SMB, ...) или даже путем выполнения сценария bash?

Функция для вывода каталога в C#:

public static List<string> ListFtpDirectory(string address, string userName, string password)
    {
        List<string> filesName = new List<string>();
        try
        {
            FtpWebRequest request = (FtpWebRequest) WebRequest.Create(address);
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(userName, password);
            request.UsePassive = true;
            using (FtpWebResponse response = (FtpWebResponse) request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                filesName =
                    reader.ReadToEnd().Split(new string[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return filesName;
    }

Любая помощь приветствуется.

1 ответ

Я не владею C#, но вы не включаете точный текст ошибки, которую получаете.

Ниже приведен скрипт Powershell, который должен работать в вашей среде:

$Server = "ftp://ftp.example.com/"
$User = "anonymous@example.com"
$Pass = "anonymous@anonymous.com"

Function Get-FtpDirectory($Directory) {

    # Credentials
    $FTPRequest = [System.Net.FtpWebRequest]::Create("$($Server)$($Directory)")
    $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($User,$Pass)
    $FTPRequest.Method = [System.Net.WebRequestMethods+FTP]::ListDirectoryDetails

    # Don't want Binary, Keep Alive unecessary.
    $FTPRequest.UseBinary = $False
    $FTPRequest.KeepAlive = $False

    $FTPResponse = $FTPRequest.GetResponse()
    $ResponseStream = $FTPResponse.GetResponseStream()

    # Create a nice Array of the detailed directory listing
    $StreamReader = New-Object System.IO.Streamreader $ResponseStream
    $DirListing = (($StreamReader.ReadToEnd()) -split [Environment]::NewLine)
    $StreamReader.Close()

    # Remove first two elements ( . and .. ) and last element (\n)
    # and take into account empty directories
    If ($DirListing.Length -gt 3) {
        $DirListing = $DirListing[2..($DirListing.Length-2)]
    }
    else {
        $DirListing = @{}    $DirListing = $DirListing[2..($DirListing.Length-2)] 
    }

    # Close the FTP connection so only one is open at a time
    $FTPResponse.Close()

    # This array will hold the final result
    $FileTree = @()

    # Loop through the listings
    foreach ($CurLine in $DirListing) {

        # Split line into space separated array
        $LineTok = ($CurLine -split '\ +')

        # Get the filename (can even contain spaces)
        $CurFile = $LineTok[8..($LineTok.Length-1)]

        # Figure out if it's a directory. Super hax.
        $DirBool = $LineTok[0].StartsWith("d")

        # Determine what to do next (file or dir?)
        If ($DirBool) {
            # Recursively traverse sub-directories
            $FileTree += ,(Get-FtpDirectory "$($Directory)$($CurFile)/")
        } Else {
            # Add the output to the file tree
            $FileTree += ,"$($Directory)$($CurFile)"
        }
    }

    Return $FileTree

}
Другие вопросы по тегам