如何在delphi中获取appdata文件夹路径

时间:2015-08-13 18:31:19

标签: delphi-7

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

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

但无效。

2 个答案:

答案 0 :(得分:8)

您无法将环境变量传递给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;

但是,无论如何,自Windows 95以来,WinExec()已被弃用,您确实应该使用CreateProcess()代替:

uses
  ..., Windows;

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

Path := GetPathToTetExe;
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;

答案 1 :(得分:0)

使用System.IOUtils的正确方法(多平台):

function GetAppDataFolder: string;                                       { Returns the path to the current user's AppData folder on Windows and to the current user's home directory on Mac OS X.   Example:  c:\Documents and Settings\Bere\Application Data\AppName\ }
begin
 Assert(System.IOUtils.TPath.HasValidFileNameChars(AppName, FALSE), 'Invalid chars in AppName: '+ AppName);
 Result:= Trail(Trail(System.SysUtils.GetHomePath)+ AppName);
end;

实用程序:

function ForceAppDataFolder: string;  // Make sure the AppDataFolder exists before you try to write the INI file there!                                      
begin
 Result:= GetAppDataFolder;
 ForceDirectories(Result);
end;

function Trail(CONST Path: string): string;    //ok  Works with UNC paths
begin
 if Path= '' then EXIT('');                                                                        { Encountered when doing something like this:  ExtractLastFolder('c:\'). ExtractLastFolder will return '' }
 Result:= IncludeTrailingPathDelimiter(Path)
end;