Introduction

Lately, I’ve updated my .NET application, SoundSwitch, to .NET Core.

In the installer, I had a full detection of the .NET Framework installed on the user’s machine. The installer is using this to suggest installing or not the required version of the .NET Framework.

Since I moved to .NET Core, I needed to update this detection, and nobody seems to have published a complete way on how to do it. Here you’ll find the code and how to use it in your own app.

Code

Here is the Pascal code to detect if the user has the wanted version of the framework or a newer version.

[Code]
function hasDotNetCore(version: string) : boolean;
var
	runtimes: TArrayOfString;
	I: Integer;
	versionCompare: Integer;
	registryKey: string;
begin
	registryKey := 'SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x64\sharedfx\Microsoft.NETCore.App';
	if(not IsWin64) then
	   registryKey :=  'SOFTWARE\dotnet\Setup\InstalledVersions\x86\sharedfx\Microsoft.NETCore.App';
	   
	Log('[.NET] Look for version ' + version);
	   
	if not RegGetValueNames(HKLM, registryKey, runtimes) then
	begin
	  Log('[.NET] Issue getting runtimes from registry');
	  Result := False;
	  Exit;
	end;
	
    for I := 0 to GetArrayLength(runtimes)-1 do
	begin
	  versionCompare := CompareVersion(runtimes[I], version);
	  Log(Format('[.NET] Compare: %s/%s = %d', [runtimes[I], version, versionCompare]));
	  if(not (versionCompare = -1)) then
	  begin
	    Log(Format('[.NET] Selecting %s', [runtimes[I]]));
	    Result := True;
	  	Exit;
	  end;
    end;
	Log('[.NET] No compatible found');
	Result := False;
end;

This part is maybe not needed for your setup since this procedure can be already present in your Inno Setup script. But if it’s not, here is the code that does the CompareVersion.

// It's quite possible that this function is already available to you in Inno Setup but in case it's not, here is the Compare Version code from stack overflow
// https://stackoverflow.com/questions/37825650/compare-version-strings-in-inno-setup
[Code]
function CompareVersion(V1, V2: string): Integer;
var
  P, N1, N2: Integer;
begin
  Result := 0;
  while (Result = 0) and ((V1 <> '') or (V2 <> '')) do
  begin
    P := Pos('.', V1);
    if P > 0 then
    begin
      N1 := StrToInt(Copy(V1, 1, P - 1));
      Delete(V1, 1, P);
    end
      else
    if V1 <> '' then
    begin
      N1 := StrToInt(V1);
      V1 := '';
    end
      else
    begin
      N1 := 0;
    end;

    P := Pos('.', V2);
    if P > 0 then
    begin
      N2 := StrToInt(Copy(V2, 1, P - 1));
      Delete(V2, 1, P);
    end
      else
    if V2 <> '' then
    begin
      N2 := StrToInt(V2);
      V2 := '';
    end
      else
    begin
      N2 := 0;
    end;

    if N1 < N2 then Result := -1
      else
    if N1 > N2 then Result := 1;
  end;
end;