Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Download an FTP Text File into a StringBuilder

See more FTP Examples

Demonstrates the Chilkat Ftp2.GetFileSb method, which downloads a remote text file, decodes it with a charset, and appends the text to a StringBuilder. The arguments are the remote file path, the charset, and the StringBuilder.

Background: When the remote file is text and you want its content as characters, this decodes it in one step so you can parse or display it directly. The charset must match the file's actual encoding or the text will be garbled. Like GetFileBd it appends, so clear the StringBuilder first if you want only this file's text.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Ftp2,
  Chilkat.StringBuilder;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  ftp: TFtp2;
  sb: TStringBuilder;
  fileText: string;

begin
  success := False;

  //  Demonstrates the Ftp2.GetFileSb method, which downloads a remote text file, decodes it, and
  //  appends the text to a StringBuilder.  The 1st argument is the remote file path, the 2nd is the
  //  charset, and the 3rd is the StringBuilder.

  ftp := TFtp2.Create;

  ftp.Hostname := 'ftp.example.com';
  ftp.Username := 'myFtpLogin';

  //  Normally you would not hard-code the password in source.  You should instead obtain it
  //  from an interactive prompt, environment variable, or a secrets vault.
  ftp.Password := 'myPassword';

  success := ftp.Connect();
  if (success = False) then
    begin
      WriteLn(ftp.LastErrorText);
      Exit;
    end;

  //  The StringBuilder is not cleared automatically, so clear it first for replacement behavior.
  sb := TStringBuilder.Create;
  success := ftp.GetFileSb('public_html/data.csv','utf-8',sb);
  if (success = False) then
    begin
      WriteLn(ftp.LastErrorText);
      Exit;
    end;

  WriteLn('Characters downloaded: ' + sb.Length);
  fileText := sb.GetAsString();
  WriteLn(fileText);

  success := ftp.Disconnect();
  if (success = False) then
    begin
      WriteLn(ftp.LastErrorText);
      Exit;
    end;


  ftp.Free;
  sb.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.