Home
What's New
Delphi 3.0 Tips
Questions
Development Tools
Links

Conversion between Long and Short File Names

{returns long file name version of fName;
 an exception will be raised if fName
 does not exist; fName can be a path}
function LongNameOf (const fName : TFileName) : TFileName;
var
  SearchRec : TSearchRec;
  i : integer;
begin
  //get rid of possible trailing \
  i := length (fName);
  if i = 0 then exit;
  if fName[i] = '\' then dec (i);
  result := copy (fName, 1, i);

  //FindFirst returns 0 iff successful
  i := FindFirst (result, faAnyFile, SearchRec);
  if i = 0 then
    result := LongNameOf (ExtractFilePath (result)) + '\' + SearchRec.Name
  else if length (result) > 2 then
    raise Exception.Create ('cannot convert "' + fName + '" to long file name');
end;

{returns short file name version of fName;
 an exception will be raised if fName
 does not exist; fName can be a path}
function ShortNameOf (const fName : TFileName) : TFileName;
var SearchRec : TSearchRec;

  {if cAlternateFileName = cFileName, then
   cAlternateFileName sometimes = nil}
  function NotNullName : string;
  begin
    if TFileName (SearchRec.FindData.cAlternateFileName) = '' then
      result := TFileName (SearchRec.FindData.cFileName)
    else
      result := TFileName (SearchRec.FindData.cAlternateFileName);
  end;

var i : integer;
begin
  //get rid of possible trailing \
  i := length (fName);
  if i = 0 then exit;
  if fName[i] = '\' then dec (i);
  result := copy (fName, 1, i);

  //FindFirst returns 0 iff successful
  i := FindFirst (result, faAnyFile, SearchRec);
  {SearchRec.FindData.cAlternateFileName is DOS file name
   of fName as PChar without path}
  if i = 0 then
    result := ShortNameOf (ExtractFilePath (result)) + '\' + NotNullName
  else if length (result) > 2 then
    raise Exception.Create ('cannot convert "' + fName + '" to short file name')
  else result := UpperCase (result);
end;