首页 > 解决方案 > 从 Inno Setup 中的 JSON 文件读取安装路径

问题描述

我想为 Inno Setup 创建一个脚本,其中安装路径将从定义目录中的文件中获取 - 没有注册表。我想它需要为它编写特定的代码,其中将定义一些变量,该变量将包含读取文件后的值。对于任何用户,文件的路径和名称始终相同,因此唯一更改的值是安装路径。

完整InstallLocation的结构,变量在哪里:

{
    "FormatVersion": 0,
    "bIsIncompleteInstall": false,
    "AppVersionString": "1.0.1",
    ...
    "InstallLocation": "h:\\Program Files\\Epic Games\\Limbo",
    ...
}

对可以做到这一点的理想代码有什么想法吗?

谢谢

标签: inno-setuppascalscript

解决方案


实现一个脚本常量来为DefaultDirName指令提供值。

您可以使用JsonParser 库来解析 JSON 配置文件。

[Setup]
DefaultDirName={code:GetInstallLocation}

[Code]

#include "JsonParser.pas"

// Here go the other functions the below code needs.
// See the comments at the end of the post.

const
  CP_UTF8 = 65001;

var
  InstallLocation: string;

<event('InitializeSetup')>
function InitializeSetupParseConfig(): Boolean;
var
  Json: string;
  ConfigPath: string;
  JsonParser: TJsonParser;
  JsonRoot: TJsonObject;
  S: TJsonString;
begin
  Result := True;
  ConfigPath := 'C:\path\to\config.json';
  Log(Format('Reading "%s"', [ConfigPath]));
  if not LoadStringFromFileInCP(ConfigPath, Json, CP_UTF8) then
  begin
    MsgBox(Format('Error reading "%s"', [ConfigPath]), mbError, MB_OK);
    Result := False;
  end
    else
  if not ParseJsonAndLogErrors(JsonParser, Json) then
  begin
    MsgBox(Format('Error parsing "%s"', [ConfigPath]), mbError, MB_OK);
    Result := False;
  end
    else
  begin 
    JsonRoot := GetJsonRoot(JsonParser.Output);
    if not FindJsonString(JsonParser.Output, JsonRoot, 'InstallLocation', S) then
    begin
      MsgBox(Format('Cannot find InstallLocation in "%s"', [ConfigPath]),
        mbError, MB_OK);
      Result := False;
    end
      else
    begin
      InstallLocation := S;
      Log(Format('Found InstallLocation = "%s"', [InstallLocation]));
    end;
    ClearJsonParser(JsonParser);
  end;
end;

function GetInstallLocation(Param: string): string;
begin
  Result := InstallLocation;
end;

该代码使用以下函数:


推荐阅读