In the previous article, we discussed RFC 959, which defines how an FTP server should work. We also walked through some of the commands that are used in this protocol. In this article, we will be creating an example FTP server in Delphi.
The Implementation of an FTP Server - Making and Removing Directories (Page 5 of 6 )
The MakeDirectory command enables us to create a new directory on the server side. The event below does that by using Delphi's CreateDir function:
procedure TForm1.IdFTPServer1MakeDirectory(ASender:TIdFTPServerContext;
var VDirectory: String);
var
ldir:string;
begin
ldir:= setslashes(Homedir+VDirectory);
if not DirectoryExists(ldir) then
if not CreateDir(ldir) then
raise Exception.Create('Cannot create '+ldir);
end;
The retrieve file event enables the client to download a file. We use Tstreams to open and read a given file:
procedure TForm1.IdFTPServer1RetrieveFile(ASender:TIdFTPServerContext;
const AFileName: String; var VStream: TStream);
begin
VStream := TFileStream.Create(setSlashes
(HomeDir+AFilename),fmOpenRead);
end;
procedure TForm1.IdFTPServer1RenameFile(ASender:TIdFTPServerContext;
const ARenameFromFile, ARenameToFile: String);
begin
if not Renamefile(ARenameFromFile,ARenameToFile) then
begin
Raise Exception.Create('Could not rename file');
end;
end;
The event below executes when the client requests a directory to be removed. Here we use Delphi's RemoveDir() function to delete a directory:
procedure TForm1.IdFTPServer1RemoveDirectory(ASender:TIdFTPServerContext;
var VDirectory: String);
Var
LFile : String;
begin
LFile := setslashes(homedir + VDirectory);
if directoryexists(LFile) then begin
RemoveDir(LFile);
end
else
begin
Raise Exception.Create('Could not remove directory');
end;
end;