Check installed .NET runtime version from C#

Jan Hovorka 0 Reputation points
2023-01-25T14:08:18.9133333+00:00

Hello,

what is the best way how to check all installed .NET runtime versions from C# code?

Is there some registry key I could read? e.g. SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\hostfxr

Or do I need to call "dotnet --list-runtimes" via System.Diagnostics.Process.Start().

Thank You For Answer.

Jan

Developer technologies .NET .NET Runtime
Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 90,681 Reputation points
    2023-01-25T14:53:42.9333333+00:00

    "dotnet --list-runtimes" just enumerates subfolders from "C:\Program Files\dotnet\shared"

    with FindFirstFileEx and so on

    0 comments No comments

  2. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2023-01-25T17:41:30.12+00:00

    I'd use dotnet --list-runtimes like this:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    public static class DotNetHelper
    {
        public static List<string> ListRuntimes()
        {
            var dotnet = Process.Start(new ProcessStartInfo("dotnet", "--list-runtimes")
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardError = true,
                RedirectStandardOutput = true,
            });
            dotnet.WaitForExit();
            string result = dotnet.StandardOutput.ReadToEnd().TrimEnd();
            string errors = dotnet.StandardError.ReadToEnd().TrimEnd();
    
            if (!string.IsNullOrEmpty(errors))
                throw new Exception(errors);
            return result.Split(new string[] { Environment.NewLine },
                StringSplitOptions.RemoveEmptyEntries).ToList();
        }
    }
    
    

    The one with checking the directory works as well, but I assume it's more implementation details; and relying on the CLI makes more sense IMO.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.