1

我已将“.file_5”扩展名与我的应用程序相关联,并使用 Delphi 中的 ParamStr(1) 函数显示一个消息框,其中包含文件的路径和文件名,当我使用下面的代码在资源管理器中双击它时。

procedure TForm1.FormCreate(Sender: TObject);
 var
  TheFile : string;
begin
  TheFile := ParamStr(1);  //filename for the file that was loaded
  ShowMessage(TheFile);
end;

这可行,但如果我将文件移动到另一个位置,然后是它原来所在的位置,那么显示的消息不正确。

示例:(使用 test.file_5)

该文件的原始位置在 C:\ 驱动器中,当我双击它时,我的应用程序启动并显示一个消息框,上面写着:

C:\test.file_5

这是对的。例如,如果我将同一个文件移动到包含程序文件夹等空格的目录,则显示的 Messagbox 不是

C:\Program Files\test.file_5

就像我期望的那样

C:\PROGRA~1.FILE_

这显然不是我所追求的信息,所以我的问题是如何使用 ParamStr() 函数来考虑其中包含空格的目录,或者我应该使用更好的函数来处理包含空格的目录他们。

4

3 回答 3

15

这不一定是错误的......只是资源管理器将一个短文件名传递给您的程序-而不是长文件名-。查看短名称与长名称

如果您只关心使用长文件名,您可以使用这两个名称打开文件,或者可以在 ShowMessage 之前将短文件名转换为长文件名(或实际操作文件)。使用在 Windows.pas 中定义的GetLongPathName API调用。

function ShortToLongFileName(const ShortName: string): string;
var
  outs: array[0..MAX_PATH] of char;
begin
  GetLongPathName(PChar(ShortName), OutS, MAX_PATH);
  Result := OutS;
end;

procedure TForm2.Button1Click(Sender: TObject);
var
  TheFile : string;
begin
  TheFile := ParamStr(1);  //filename for the file that was loaded
  TheFile := ShortToLongFileName(TheFile);
  ShowMessage(TheFile);
end;

我在 Windows Vista 下对其进行了测试,无论您提供的是短文件名还是已经长的文件名,GetLongPathName 都有效(如果文件存在,显然)

于 2010-11-03T06:32:51.810 回答
7

您的关联设置错误。而不是双击 .file_5 做

C:\YourPath\YourApp.exe %1

协会应设立为

"C:\YourPathYourApp.exe" "%1"

请注意 %1 周围的双引号 - 这会保留包含的所有空格,而不是导致 Windows 传递短路径和文件名。

于 2010-11-03T13:17:03.080 回答
-1

使用此功能自行解决。


Function GetLongPathAndFilename(Const S : String) : String;

Var srSRec : TSearchRec; iP,iRes : Integer; sTemp,sRest : String; Bo : Boolean;

Begin Result := S + ' [directory not found]'; // Check if file exists Bo := FileExists(S); // Check if directory exists iRes := FindFirst(S + '*.*',faAnyFile,srSRec); // If both not found then exit If ((not Bo) and (iRes <> 0)) then Exit; sRest := S; iP := Pos('\',sRest); If iP > 0 then Begin sTemp := Copy(sRest,1,iP - 1); // Drive sRest := Copy(sRest,iP + 1,255); // Path and filename End else Exit; // Get long path name While Pos('\',sRest) > 0 do begin iP := Pos('\',sRest); If iP > 0 then Begin iRes := FindFirst(sTemp + '\' + Copy(sRest,1,iP - 1),faAnyFile,srSRec); sRest := Copy(sRest,iP + 1,255); If iRes = 0 then sTemp := sTemp + '\' + srSRec.FindData.cFileName; End; End; // Get long filename If FindFirst(sTemp + '\' + sRest,faAnyFile,srSRec) = 0 then Result := sTemp + '\' + srSRec.FindData.cFilename; SysUtils.FindClose(srSRec); End;

于 2010-11-03T06:24:58.370 回答