将注册表中的版本号转换为System.Version?

时间:2012-05-25 10:07:28

标签: c# .net registry version

我正在从注册表中检索版本号,如下所示:

rKey.GetValue("Version")

现在我想将其转换为System.Version对象 我该怎么做?

2 个答案:

答案 0 :(得分:2)

假设这是一个字符串......

string versionText = (string) rKey.GetValue("Version");
Version version = new Version(versionText);

答案 1 :(得分:1)

假设这是一个REG_DWORD(通常在卸载注册表项中找到)...

According to MSDN此密钥为"来自ProductVersion属性"。
它描述了3个字段:Major,Minor和Build。

DWORD值(以十六进制表示)可以通过以下方式分解:

  

0xMMmmBBBB
  其中MM =主要版本,mm =次要版本,BBBB =构建。

这是我的MCVE

Action shot

主窗口:

<Window x:Class="RegVersionParse.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:RegVersionParse"
        Height="150" Width="500"
        Title="Uninstall Registry Key ProductVersion Decoder">
    <Window.Resources>
        <l:VersionConverter x:Key="OutConvert"/>
    </Window.Resources>
    <StackPanel>
        <Label Margin="0,10,0,0" FontSize="10"
            Content="Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
               &#x0a;    Input  REG_DWORD  Version  (as Decimal)"/>
        <StackPanel Orientation="Horizontal" Margin="20,15,0,5">
            <Label Content="Input: "/>
            <TextBox MinWidth="100" Text="{Binding MyInputVersion, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
            <Label Content="Output: " Margin="40,0,0,0"/>
            <TextBox MinWidth="100" Text="{Binding MyOutput, Converter={StaticResource OutConvert}}" 
                     IsReadOnly="True" Background="{Binding StatusColor}"/>
        </StackPanel>
    </StackPanel>
</Window>

MainWindow.xaml.cs

using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.ComponentModel;
using System.Globalization;

namespace RegVersionParse
{
    [ValueConversion(typeof(Version), typeof(string))]
    public class VersionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) { return "Not A Version"; }
            return value.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }

    /// <summary>Interaction logic for MainWindow.xaml</summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        string myInput;
        public string MyInputVersion
        {
            get { return myInput; }
            set
            {
                if (myInput != value)
                {
                    myInput = value;
                    MyOutput = RegDwordIntegerVersionParse(value);               
                    RaisePropertyChanged();
                }
            }
        }

        Version myOutput;
        public Version MyOutput
        {
            get { return myOutput; }
            set { if (myOutput != value) { myOutput = value; RaisePropertyChanged(); } }
        }

        Brush statusColor;
        public Brush StatusColor
        {
            get { return statusColor; }
            set { if (statusColor != value) { statusColor = value; RaisePropertyChanged(); } }
        }

        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            StatusColor = new SolidColorBrush(Colors.Green);
        }

        /// <summary>
        /// This function is designed specifically for producing a 
        /// System.Version object from the Uninstall information
        /// ("Version" key) in the Windows registry for a given app.
        /// </summary>
        /// <param name="input">Using the Registry class to obtain a 
        /// REG_DWORD value for an installed application, 
        /// Input the integer value as a string.</param>
        /// <returns>System Version Object (Major, Minor, Build) </returns>
        public System.Version RegDwordIntegerVersionParse(string input)
        {
            string HexMajor = string.Empty;
            string HexMinor = string.Empty;
            string HexBuild = string.Empty;
            int Major = -1;
            int Minor = -1;
            int Build = -1;

            try
            {
                //int numVersion = int.Parse(input);
                Int64 numVersion = Int64.Parse(input); 

                string hexVersion = numVersion.ToString("X8");

                // Could also check for alphanumeric...
                if (!string.IsNullOrEmpty(hexVersion) && hexVersion.Length >= 5)
                {
                    HexMajor = hexVersion.Substring(0, 2);
                    HexMinor = hexVersion.Substring(2, 2);

                    // The Build number could be up to 4 characters, but might be less!
                    HexBuild = hexVersion.Substring(4, hexVersion.Length - 4);

                    Major = int.Parse(HexMajor, System.Globalization.NumberStyles.HexNumber);
                    Minor = int.Parse(HexMinor, System.Globalization.NumberStyles.HexNumber);
                    Build = int.Parse(HexBuild, System.Globalization.NumberStyles.HexNumber);

                    StatusColor = new SolidColorBrush(Colors.White);
                    return new Version(Major, Minor, Build);
                } 
                else 
                {
                    StatusColor = new SolidColorBrush(Colors.Orange);
                    return new Version();
                }
            }
            catch
            {
                StatusColor = new SolidColorBrush(Colors.Red);
                return new Version();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) =>
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}