Last directory folder

8

How do I get the last folder in a directory. Ex:

C:\Program Files\Skype

The last folder would be Skype.

    
asked by anonymous 29.10.2014 / 00:08

3 answers

7

To avoid possible wrong results, I would do it as follows

program ConsoleTestApp;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

function ObterNomeUltimaPasta(path: string): string;
var
  pathAjustado: string;
begin
  pathAjustado := path;
  if FileExists(pathAjustado) then
    pathAjustado := ExtractFileDir(pathAjustado);

  Result := ExtractFileName(ExcludeTrailingPathDelimiter(pathAjustado));
end;

begin
  try
    Writeln(ObterNomeUltimaPasta('C:\Program Files\GIMP 2\bin\bz2-1.dll'));
    Writeln(ObterNomeUltimaPasta('C:\Program Files\GIMP 2\bin\'));
    Writeln(ObterNomeUltimaPasta('C:\Program Files\GIMP 2\bin'));
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

The result of the console was

  

bin
  bin
  bin

    
29.10.2014 / 12:53
9

You can use the ExtractFileName() function to extract the name of a file or folder, the result will be the characters to the right of the string passed as a parameter, starting with the first character after the # or backslash .

If the result of the above function contains a delimiter at the end you can use the ExcludeTrailingPathDelimiter() to delete it.

uses
  SysUtils;

function GetPath(const pPath: string): string;
begin
if ExtractFileExt(pPath) <> '' then
  Result := ExtractFileName(ExtractFileDir(pPath))
else
  Result := ExtractFileName(ExcludeTrailingPathDelimiter(pPath));
end;

To use:

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(GetPath('C:\Program Files\Skype'));            // Skype
ShowMessage(GetPath('C:\Program Files\Skype\'));           // Skype
ShowMessage(GetPath('C:\Program Files\Skype\Skype.exe'));  // Skype
end;
    
29.10.2014 / 00:33
6

You need to break the string "C: \ Program Files \ Skype" into the "\", like this:

program Project28;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;

procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
   ListOfStrings.Clear;
   ListOfStrings.Delimiter     := Delimiter;
   ListOfStrings.DelimitedText := Str;
end;


var
   OutPutList: TStringList;
begin
   OutPutList := TStringList.Create;
   try
     Split('\', 'C:\Program Files\Skype', OutPutList) ;
     Writeln(OutPutList.Text);
     Readln;
   finally
     OutPutList.Free;
   end;
end.

The result will be:

List[0] = 'C:'
List[1] = 'Program Files'
List[2] = 'Skype'

You just have to grab the List [2] to get the last folder.

Another option is to use the ExtractFileName function:

uses
  SysUtils;

var
    Filepath : string ;
begin
  Filepath:='C:\Program Files\Skype';
  ShowMessage(ExtractFileName(Path));

where the result is

Skype
    
29.10.2014 / 00:26