Page 1 of 1

List of file

Posted: Mon 31 Oct 2011 09:28
by Gunboule
Hi,
I'm new in using SFTPclient in Delphi BDS 2006.
I can connect in ssh then sftp to my server and i want to know how i can get the number of file in a directory and their names?

Thanks

Posted: Tue 01 Nov 2011 10:13
by Dimon
Below you can see a simple code piece to download a list of files and directories.

Code: Select all

procedure TForm1.ScSSHClientServerKeyValidate(Sender: TObject; NewServerKey: TScKey; var Accept: Boolean);
begin
  Accept := True;
end;

procedure TForm1.ScSFTPClientDirectoryList(Sender: TObject; const Path: string;
const Handle: TBytes; FileInfo: TScSFTPFileInfo; EOF: Boolean);
begin
  if (FileInfo = nil) or (FileInfo.Filename = '.') then
    Exit;

  if (Length(FileInfo.Longname) > 0) and (FileInfo.Longname[1] = 'd') then
    MemoDirs.Lines.Add(FileInfo.Filename)
  else
    MemoFiles.Lines.Add(FileInfo.Filename);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ScSSHClient: TScSSHClient;
  ScFileStorage: TScFileStorage;
  ScSFTPClient: TScSFTPClient;
  Handle: TScSFTPFileHandle;
begin
  ScFileStorage := TScFileStorage.Create(nil);
  ScSSHClient := TScSSHClient.Create(nil);
  ScSSHClient.KeyStorage := ScFileStorage;
  ScSSHClient.OnServerKeyValidate := ScSSHClientServerKeyValidate;
  ScSSHClient.HostName := 'host';
  ScSSHClient.User := 'user';
  ScSSHClient.Password := 'pass';
  ScSSHClient.Connect;

  ScSFTPClient := TScSFTPClient.Create(nil);
  ScSFTPClient.SSHClient := ScSSHClient;
  ScSFTPClient.OnDirectoryList := ScSFTPClientDirectoryList;
  ScSFTPClient.Initialize;
  Handle := ScSFTPClient.OpenDirectory('.');
  try
    MemoDirs.Lines.Clear;
    MemoFiles.Lines.Clear;
    repeat
      ScSFTPClient.ReadDirectory(Handle);
    until ScSFTPClient.EOF;
  finally
    ScSFTPClient.CloseHandle(Handle);
  end;
end;
To use this code, you should add the ScBridge, ScSSHClient, ScSFTPClient, ScCLRClasses, and ScSFTPUtils units to the uses clause of your unit.

You may look into SFTPClient demo to get complete information about this functionality.

Posted: Wed 02 Nov 2011 09:10
by Gunboule
I saw in the demo the ScSFTPClientDirectoryList but i forgot this line
ScSFTPClient.OnDirectoryList := ScSFTPClientDirectoryList;
:/


Thanks for helping !