Delphi 在长文件名和短文件名之间转换


本文整理自网络,侵删。

 
uses
  Windows, SysUtils;

function GetShortName(sLongName: string): string;
var
  sShortName    : string;
  nShortNameLen : integer;
begin
  SetLength(sShortName, MAX_PATH);
  nShortNameLen := GetShortPathName(
    PChar(sLongName), PChar(sShortName), MAX_PATH - 1
  );
  if (0 = nShortNameLen) then
  begin
    // handle errors...
  end;
  SetLength(sShortName, nShortNameLen);
  Result := sShortName;
end;

现在是一个将短文件名转换为长文件名的函数:

uses
  Windows, SysUtils;

function __GetLongName(sShortName: string; var bError : boolean): string;
var
  bAddSlash : boolean;
  SearchRec : TSearchRec;
  nStrLen   : integer;
begin
  bError    := False;
  Result    := sShortName;
  nStrLen   := Length(sShortName);
  bAddSlash := False;

  if('\' = sShortName[nStrLen]) then
  begin
    bAddSlash := True;
    SetLength(sShortName, nStrLen - 1);
    dec(nStrLen);
  end;

  if (nStrLen - Length(ExtractFileDrive(sShortName))) > 0 then
  begin
    if 0 = FindFirst(sShortName, faAnyFile, SearchRec) then
    begin
      Result := ExtractFilePath(sShortName) + SearchRec.Name;
      if bAddSlash then
      begin
        Result := Result + '\';
      end;
    end
    else
    begin
      // handle errors...
      bError := True;
    end;
    FindClose(SearchRec);
  end;
end;

function GetLongName(sShortName: string): string;
var
  s      : string;
  p      : integer;
  bError : boolean;
begin
  Result := sShortName;

  s := '';
  p := Pos('\', sShortName);
  while p > 0 do
  begin
    s := __GetLongName(s + Copy(sShortName, 1, p), bError);
    Delete(sShortName, 1, p);
    p := Pos('\', sShortName);

    if bError then
      Exit;
  end;
  if '' <> sShortName then
  begin
    s := __GetLongName(s + sShortName, bError);
    if bError then
      Exit;
  end;
  Result := s;
end;
Let's give our functions a try:

procedure Test;
const
  csTest = 'C:\Program Files';
var
  sShort,
  sLong: string;
begin
  sShort := GetShortName(csTest);
  MessageDlg(
    'Short name for "' + csTest + '" is "' + sShort + '"',
    mtInformation, [mbOk], 0
  );
  sLong := GetLongName(sShort);
  MessageDlg(
    'Long name for "' + sShort + '" is "' + sLong + '"',
     mtInformation, [mbOk], 0
  );
end;

相关阅读 >>

Delphi xe2和xe3开发的程序中加入管理员权限申请

Delphi android 启动卡死处理方法

Delphi 通过api 隐藏任务栏所有托盘图标

crossbow病毒开放源代码-熊猫烧香源始代码

Delphi fdconnection取得excel工作表名

Delphi 如何快速从列表框tlistbox中删除重复项

Delphi 使用泛型的 tarray 从动态数组中查找指定元素

Delphi 对gzip解压

Delphi窗口随机类名

Delphi的控制台程式添加图标

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...