You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Inno Setup获取用户下载文件夹路径?

正确获取Inno Setup中用户下载文件夹路径的方法

你的代码执行else分支的核心问题是硬编码的下载文件夹路径不可靠:

  • {%username%}不是Inno Setup的合法常量,正确的用户主目录常量是{userprofile},但即使如此,用户的下载文件夹也可能因系统设置(比如迁移到其他盘符)不在{userprofile}\Downloads下;
  • Inno Setup确实没有内置的下载文件夹常量,必须通过Windows系统API来获取标准路径。

解决方案:调用Windows API SHGetKnownFolderPath

Windows提供了SHGetKnownFolderPath函数来获取系统标准文件夹的路径,其中下载文件夹对应的GUID是{374DE290-123F-4565-9164-39C4925E467B}。以下是修正后的完整代码:

[Code]
const
  FOLDERID_Downloads = '{374DE290-123F-4565-9164-39C4925E467B}';
  SIGDN_FILESYSPATH = 0;

type
  HResult = Longint;

function SHGetKnownFolderPath(const rfid: TGUID; dwFlags: DWORD; hToken: THandle; out ppszPath: PWideChar): HResult;
  external 'SHGetKnownFolderPath@shell32.dll stdcall';

function InitializeSetup(): Boolean;
var
  DownloadPath: PWideChar;
  FilePath: string;
  Hr: HResult;
begin
  Result := False;
  // 调用API获取下载文件夹路径
  Hr := SHGetKnownFolderPath(StringToGUID(FOLDERID_Downloads), 0, 0, DownloadPath);
  if Hr = 0 then
  begin
    try
      FilePath := DownloadPath + '\file.txt';
      if FileExists(FilePath) then
      begin
        MsgBox('Installation validated', mbInformation, MB_OK);
        Result := True;
      end
      else
      begin
        MsgBox('Abort installation: file not found', mbCriticalError, MB_OK);
      end;
    finally
      // 释放API返回的内存
      CoTaskMemFree(DownloadPath);
    end;
  end
  else
  begin
    MsgBox('Failed to get Downloads folder path', mbCriticalError, MB_OK);
  end;
end;

代码说明

  1. API声明:SHGetKnownFolderPath来自shell32.dll,需要正确声明参数和返回值类型;
  2. GUID标识:FOLDERID_Downloads是系统定义的下载文件夹唯一标识,确保无论系统设置如何都能拿到正确路径;
  3. 内存释放:API返回的路径内存需要用CoTaskMemFree释放,避免内存泄漏;
  4. 错误处理:检查API调用的返回值(Hr=0表示成功),同时处理文件不存在的情况。

内容的提问来源于stack exchange,提问作者Rahul Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:10:33