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#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 91,501 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,996 Reputation points 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' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.