获取appdata文件夹路径

获取appdata文件夹路径

如何获取appdata文件夹路径?这是我的代码:

begin
Winexec(PAnsichar('%appdata%\TEST.exe'), sw_show);
end;
end.

,但不起作用。

最佳答案

您不能将环境变量传递给WinExec()。您必须先解决它们,例如:

uses
  ..., SysUtils;

function GetPathToTestExe: string;
begin
  Result := SysUtils.GetEnvironmentVariable('APPDATA');
  if Result <> '' then
    Result := IncludeTrailingPathDelimiter(Result) + 'TEST.exe';
end;
uses
  ..., Windows;

var
  Path: string;
begin
  Path = GetPathToTestExe;
  if Path <> '' then
    WinExec(PAnsiChar(Path), SW_SHOW);
end;

或者:
uses
  ..., SysUtils, Windows;

function GetPathToTestExe: string;
var
  Path: array[0..MAX_PATH+1] of Char;
begin
  if ExpandEnvironmentStrings('%APPDATA%', Path, Length(Path)) > 1 then
    Result := IncludeTrailingPathDelimiter(Path) + 'TEST.exe'
  else
    Result := '';
end;

获取APPDATA文件夹路径的一种更可靠(且官方)的方法是改用SHGetFolderPath()(或在Vista +上为SHGetKnownFolderPath()),例如:
uses
  ..., SysUtils, Windows, SHFolder;

function GetPathToTestExe: string;
var
  Path: array[0..MAX_PATH] of Char;
begin
  if SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, Path) = S_OK then
    Result := IncludeTrailingPathDelimiter(Path) + 'TEST.exe'
  else
    Result := '';
end;

或者:
uses
  ..., SysUtils;

function GetPathToTestExe: string;
var
  Path: string;
begin
  // GetHomePath() uses SHGetFolderPath(CSIDL_APPDATA) internally...
  Path := SysUtils.GetHomePath;
  if Path <> '' then
    Result := IncludeTrailingPathDelimiter(Path) + 'TEST.exe'
  else
    Result := '';
end;

但是,无论如何,自Windows 95起就不推荐使用WinExec()了,您实际上应该改用CreateProcess(),例如:
uses
  ..., Windows;

var
  Path: String;
  si: TStartupInfo;
  pi: TProcessInformation;

Path := GetPathToTestExe;
if Path <> '' then
begin
  ZeroMemory(@si, SizeOf(si));
  si.cb := SizeOf(si);
  si.dwFlags := STARTF_USESHOWWINDOW;
  si.wShowWindow := SW_SHOW;

  if CreateProcess(nil, PChar(Path), nil, nil, FALSE, 0, nil, nil, @si, pi)
  begin
    //...
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
  end;
end;

关于delphi-7 - 如何在delphi中获取appdata文件夹路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31995872/

10-16 14:00