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

C#
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.
10,198 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,117 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 81,461 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,936 Reputation points MVP
    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.