【C#】StdRegProvを使ったレジストリ操作

書き直すのが面倒なのでコードとリンクだけはっつけておきます。

[20140210追記]ちゃんと書き直しました。

コード

using System;
using System.Linq.Expressions;
using System.Management;

namespace RegistryTest
{
    public class Registry : IDisposable
    {
        public enum DefKey : uint
        {
            HKEY_CLASSES_ROOT = 2147483648,
            HKEY_CURRENT_USER = 2147483649,
            HKEY_LOCAL_MACHINE = 2147483650,
            HKEY_USERS = 2147483651,
            HKEY_CURRENT_CONFIG = 2147483653,
        }

        private readonly ManagementClass _mc;

        public Registry()
        {
            _mc = new ManagementClass("StdRegProv");
        }

        public string[] GetEnumKeys(DefKey root, string path)
        {
            return InvokeMethod<string[]>("EnumKey", "sNames", hDefKey => (uint)root, sSubKeyName => path);
        }

        public string GetStringValue(DefKey root, string path, string valueName = "")
        {
            return InvokeMethod<string>("GetStringValue", "sValue", hDefKey => (uint)root, sSubKeyName => path, sValueName => valueName);
        }

        private T InvokeMethod<T>(string methodName, string outPropertyName, params Expression<Func<object, object>>[] args)
        {
            using (var inParam = _mc.GetMethodParameters(methodName))
            {
                foreach (var arg in args)
                {
                    var argValue = arg.Compile().Invoke(null);
                    if (argValue == null) continue;

                    inParam[arg.Parameters[0].Name] = argValue;
                }

                using (var outParam = _mc.InvokeMethod(methodName, inParam, null))
                {
                    return (T)outParam[outPropertyName];
                }
            }
        }

        public void Dispose()
        {
            _mc.Dispose();
        }
    }
}

リンク