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

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

本文介绍了如何在delphi中获取appdata文件夹路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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

但不起作用。

推荐答案

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

You cannot pass environment variables to WinExec(). You have to resolve them first, eg:

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()),例如:

A more reliable (and official) way to get the APPDATA folder path is to use SHGetFolderPath() (or SHGetKnownFolderPath() on Vista+) instead, eg:

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;

但是在任何情况下, WinExec()从Windows 95开始不推荐使用,实际上您应该使用 CreateProcess(),例如:

But, in any case, WinExec() has been deprecated since Windows 95, you really should be using CreateProcess() instead, eg:

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中获取appdata文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:13