EvoCorp Home    Delphi::Advance

 

 

   

 

GetFileNameComponent

Whilst the Delphi SysUtils unit comes with an array of useful filename and file-oriented functions, there's been one function that I seem to continually transfer across projects.

The GetFileNameComponent function, below, is a simple function that enables the developer to extract the major portions of a filename from a single function call. It's nothing special or advanced, it's just something that I find useful.

type
  // ncExtension returns the file extension without the period (.)
  // ncFileName returns the file name, including the extension
  // ncFileNameNoExt returns the file name without the extension
  //   or trailing period (.)
  // ncFolder returns the path, including the colon or backslash
  //   that separates the path from the file name.

  TFileNameComponent = (ncExtension, ncFileName, ncFileNameNoExt, ncFolder);
 
function GetFileNameComponent(const AFileName: string;
  AFileNameComponent: TFileNameComponent): string;
var i: Integer;
begin
  case AFileNameComponent of
    ncExtension: begin
                   Result := ExtractFileExt(AFileName);
                   if (Length(Result) > 0) and (Result[1] = '.') then
                     System.Delete(Result, 1, 1);
                 end;
    ncFileName: Result := ExtractFileName(AFileName);
    ncFileNameNoExt: begin
                       Result := ExtractFileName(AFileName);
                       i := LastDelimiter('.', Result);
                       if i > 0 then
                         System.Delete(Result, i, Length(Result) - i + 1);
                     end;
    ncFolder: Result := ExtractFilePath(AFileName);
  else Result := '';
  end;
end;

 

This space for rent :)