13/03/2026

Lưu và đọc thông tin từ Registry trong dotNet c# | AutoCAD dotNet

Ứng dụng được phát triển/Sưu tầm bởi đội ngũ AutoLISP Thật là đơn giản
   

Thông tin thêm: 👉👉👉

Sử dụng Regs

Lưu và đọc thông tin cài đặt vào Registry bằng c#


1 Thêm class ModifyRegistry.cs

Lưu mã sau dưới dạng tệp tin ModifyRegistry.lsp
Code:
using Microsoft.Win32;
using System;
using System.Security.Cryptography;

namespace lhBasic
{
    /// <summary>
    /// An useful class to read/write/delete/count registry keys
    /// </summary>
    public class ModifyRegistry
    {
        //by lisp.vn
        public const string DefautlSubKey = "SOFTWARE\\AJS\\ObjectARX";
        private bool showError = true;
        /// <summary>
        /// A property to show or hide error messages
        /// (default = false)
        /// </summary>
        ///

        public bool ShowError
        {
            get { return showError; }
            set { showError = value; }
        }

        private string subKey;

        public ModifyRegistry(string sKey)
        {
            if (!sKey.ToUpper().Contains("SOFTWARE\\"))
                subKey = DefautlSubKey + sKey;
            else
                subKey = sKey;
        }

        /// <summary>
        /// A property to set the SubKey value
        /// (default = "SOFTWARE\\" + Application.ProductName.ToUpper())
        /// </summary>
        public string SubKey
        {
            get { return subKey; }
            set { subKey = value; }
        }

        private RegistryKey baseRegistryKey = Registry.CurrentUser;

        /// <summary>
        /// A property to set the BaseRegistryKey value.
        /// (default = Registry.LocalMachine)
        /// </summary>
        public RegistryKey BaseRegistryKey
        {
            get { return baseRegistryKey; }
            set { baseRegistryKey = value; }
        }

        /* **************************************************************************
         * **************************************************************************/

        /// <summary>
        /// To read a registry key.
        /// input: KeyName (string)
        /// output: value (string)
        /// </summary>
        public string Read(string KeyName)
        {
            // Opening the registry key
            RegistryKey rk = baseRegistryKey;
            // Open a subKey as read-only
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            // If the RegistrySubKey doesn't exist -> (null)
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                    // If the RegistryKey exists I get its value
                    // or null is returned.
                    return (string)sk1.GetValue(KeyName.ToUpper());
                }
                catch (Exception e)
                {
                    // AAAAAAAAAAARGH, an error!
                    ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
                    return null;
                }
            }
        }

        public object Readobject(string KeyName)
        {
            // Opening the registry key
            RegistryKey rk = baseRegistryKey;
            // Open a subKey as read-only
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            // If the RegistrySubKey doesn't exist -> (null)
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                    // If the RegistryKey exists I get its value
                    // or null is returned.
                    return sk1.GetValue(KeyName.ToUpper());
                }
                catch (Exception e)
                {
                    // AAAAAAAAAAARGH, an error!
                    ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
                    return null;
                }
            }
        }

        /* **************************************************************************
         * **************************************************************************/

        /// <summary>
        /// To write into a registry key.
        /// input: KeyName (string) , Value (object)
        /// output: true or false
        /// </summary>
        public bool Write(string KeyName, object Value)
        {
            if (Value == null) return false;
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                // I have to use CreateSubKey
                // (create or open it if already exits),
                // 'cause OpenSubKey open a subKey as read-only
                RegistryKey sk1 = rk.CreateSubKey(subKey);
                // Save the value
                sk1.SetValue(KeyName.ToUpper(), Value);

                return true;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Writing registry " + KeyName.ToUpper());
                return false;
            }
        }

        /* **************************************************************************
         * **************************************************************************/

        /// <summary>
        /// To delete a registry key.
        /// input: KeyName (string)
        /// output: true or false
        /// </summary>
        public bool DeleteKey(string KeyName)
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.CreateSubKey(subKey);
                // If the RegistrySubKey doesn't exists -> (true)
                if (sk1 == null)
                    return true;
                else
                    sk1.DeleteValue(KeyName);

                return true;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Deleting SubKey " + subKey);
                return false;
            }
        }

        /* **************************************************************************
         * **************************************************************************/

        /// <summary>
        /// To delete a sub key and any child.
        /// input: void
        /// output: true or false
        /// </summary>
        public bool DeleteSubKeyTree()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists, I delete it
                if (sk1 != null)
                    rk.DeleteSubKeyTree(subKey);

                return true;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Deleting SubKey " + subKey);
                return false;
            }
        }

        /* **************************************************************************
         * **************************************************************************/

        /// <summary>
        /// Retrive the count of subkeys at the current key.
        /// input: void
        /// output: number of subkeys
        /// </summary>
        public int SubKeyCount()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists...
                if (sk1 != null)
                    return sk1.SubKeyCount;
                else
                    return 0;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Retriving subkeys of " + subKey);
                return 0;
            }
        }

        public string[] Subkeys()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists...
                if (sk1 != null)
                    return sk1.GetSubKeyNames();
                else
                    return null;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Retriving subkeys of " + subKey);
                return null;
            }
        }

        public string[] Subvalues()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists...
                if (sk1 != null)
                    return sk1.GetValueNames();
                else
                    return null;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Retriving subkeys of " + subKey);
                return null;
            }
        }

        /* **************************************************************************
         * **************************************************************************/

        /// <summary>
        /// Retrive the count of values in the key.
        /// input: void
        /// output: number of keys
        /// </summary>
        public int ValueCount()
        {
            try
            {
                // Setting
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.OpenSubKey(subKey);
                // If the RegistryKey exists...
                if (sk1 != null)
                    return sk1.ValueCount;
                else
                    return 0;
            }
            catch (Exception e)
            {
                // AAAAAAAAAAARGH, an error!
                ShowErrorMessage(e, "Retriving keys of " + subKey);
                return 0;
            }
        }

        /* **************************************************************************
         * **************************************************************************/

        private void ShowErrorMessage(Exception e, string Title)
        {
            //if (showError == true) MessageBox.Show(e.Message, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //by lisp.vn
    }
}



2 Thêm class Regs.cs

Lưu mã sau dưới dạng tệp tin Regs.lsp
Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace lhBasic
{
    public enum RegTFType
    { YesNo, TrueFalse, N01, CoKhong };

    public static partial class Regs
    {
        //by lisp.vn
        public static T Get<T>(string path, string kname, T def, RegTFType tf = RegTFType.YesNo)
        {
            ModifyRegistry mdf = new ModifyRegistry(path);
            var ret = mdf.Readobject(kname);
            if (ret != null) return ret.Convert(def);

            if (def is bool b)
            {
                if (tf == RegTFType.YesNo) mdf.Write(kname, b ? "Yes" : "No");
                else if (tf == RegTFType.TrueFalse) mdf.Write(kname, b ? "true" : "false");
                else if (tf == RegTFType.N01) mdf.Write(kname, b ? "1" : "0");
                else if (tf == RegTFType.CoKhong) mdf.Write(kname, b ? "Co" : "Khong");

                ret = mdf.Readobject(kname);
                if (ret != null)
                {
                    string a = ret.ToString();
                    return (a == "1" || a.ToUpper() == "YES" || a.ToUpper() == "CO" || a.ToUpper() == "TRUE") is T t1 ? t1 : def;
                }
            }
            else
            {
                mdf.Write(kname, def);
            }

            return def;
        }

        public static T Convert<T>(this object ret, T def)
        {
            if (ret != null)
            {
                if (ret is T t)
                    return t;
                else
                {
                    if (typeof(T) == typeof(double))
                        return ret.ToString().ToDouble() is T t1 ? t1 : def;
                    else if (typeof(T) == typeof(int))
                        return ret.ToString().ToInt() is T t1 ? t1 : def;
                    else if (typeof(T) == typeof(string))
                        return ret.ToString() is T t1 ? t1 : def;
                    else if (typeof(T) == typeof(bool))
                        return ret.ToString().IsTrue() is T t1 ? t1 : def;
                }
            }
            return def;
        }

        public static bool IsTrue(this string str)
        {
            return str.Any("true", "yes", "y", "1");
        }

        public static bool Cons(this string source, string toCheck)
        {
            if (source == null || toCheck == null || source.Length < toCheck.Length) return false;
            return source.ToUpper().Contains(toCheck.ToUpper());
        }

        public static bool Any(this string txt, params object[] strs)
        {
            foreach (object s in strs)
                if (txt.Cons(s.ToString()))
                    return true;
            return false;
        }

        public static double ToDouble(this string obj, double def = 0.0)
        {
            double retval = def;
            try
            {
                double.TryParse(obj.ToString(), out retval);
            }
            catch { }
            return retval;
        }

        public static int ToInt(this string str, int def = 0)
        {
            int retval = def;
            int.TryParse(str, out retval);
            return retval;
        }

        public static void Set<T>(string path, string kname, T def, RegTFType tf = RegTFType.YesNo)
        {
            if (path != null && path != "" && def != null)
            {
                ModifyRegistry mdf = new ModifyRegistry(path);

                if (def.GetType() == typeof(bool))
                {
                    if (tf == RegTFType.YesNo) mdf.Write(kname, (def is bool b ? b : true) ? "Yes" : "No");
                    else if (tf == RegTFType.TrueFalse) mdf.Write(kname, (def is bool b ? b : true) ? "true" : "false");
                    else if (tf == RegTFType.N01) mdf.Write(kname, (def is bool b ? b : true) ? "1" : "0");
                    else if (tf == RegTFType.CoKhong) mdf.Write(kname, (def is bool b ? b : true) ? "Co" : "Khong");

                    return;
                }

                mdf.Write(kname, def);
            }
            return;
        }

        public static DateTime GetDateTime(string path, string kname)
        {
            string spath = path + "\\" + kname;
            //EDs.WriteLine(spath);
            int y = Regs.Get(spath, "Year", 1);
            int m = Regs.Get(spath, "Month", 1);
            int d = Regs.Get(spath, "Day", 1);
            int h = Regs.Get(spath, "Hour", 1);
            int mi = Regs.Get(spath, "Minute", 1);
            int s = Regs.Get(spath, "Second", 1);
            return new DateTime(y, m, d, h, mi, s);
        }

        public static string GetNotNull(string path, string kname, string value)
        {
            ModifyRegistry mdf = new ModifyRegistry(path);
            if (mdf.Readobject(kname) == null) mdf.Write(kname, value);
            string str = mdf.Readobject(kname).ToString();
            if (str == "") str = value;
            return str;
        }

        public static DateTime SetDateTime(string path, string kname)
        {
            DateTime dt = File.GetLastWriteTime(Regs.Get(path, kname, "C:\\"));
            string spath = path + "\\" + kname;
            Regs.Set(spath, "Year", dt.Year);
            Regs.Set(spath, "Month", dt.Month);
            Regs.Set(spath, "Day", dt.Day);
            Regs.Set(spath, "Hour", dt.Hour);
            Regs.Set(spath, "Minute", dt.Minute);
            Regs.Set(spath, "Second", dt.Second);
            return dt;
        }

        public static void SetDateTime(string path, string kname, DateTime dt)
        {
            string spath = path + "\\" + kname;
            Set(spath, "Year", dt.Year);
            Set(spath, "Month", dt.Month);
            Set(spath, "Day", dt.Day);
            Set(spath, "Hour", dt.Hour);
            Set(spath, "Minute", dt.Minute);
            Set(spath, "Second", dt.Second);
            return;
        }

        public static List<string> GetNames(string path)
        {
            List<string> names = new List<string>();
            try
            {
                ModifyRegistry mdf = new ModifyRegistry(path);
                var Subvalues = mdf.Subvalues();
                names = Subvalues != null && Subvalues.Length > 0 ? Subvalues.ToList() : new List<string>();
            }
            catch (System.Exception ee)
            {
                //EDs.WriteLine(ee.Message);
            }
            return names;
        }

        public static List<string> GetStrings(string path)
        {
            List<object> gets = GetValues(path);
            List<string> names = new List<string>();
            if (gets.Count > 0) foreach (object o in gets) if (!names.Contains(o.ToString())) names.Add(o.ToString());
            return names;
        }

        public static List<string> GetSubkeys(string path)
        {
            List<string> names = new List<string>();
            try
            {
                ModifyRegistry mdf = new ModifyRegistry(path);
                names = mdf.Subkeys().ToList();
            }
            catch (Exception ee)
            {
                //EDs.WriteLine(ee.Message);
            }
            return names;
        }

        public static List<Dictionary<string, object>> GetRegistryProperties(string kpath)
        {
            List<Dictionary<string, object>> tps = new List<Dictionary<string, object>>();

            try
            {
                foreach (string sub in GetSubkeys(kpath))
                {
                    //EDs.Msg("sub=" + sub);
                    Dictionary<string, object> tp = new Dictionary<string, object>();
                    ModifyRegistry mdf = new ModifyRegistry(kpath + "\\" + sub);
                    var names = mdf.Subvalues();
                    //EDs.Msg("names=" + names);

                    foreach (string n in names)
                    {
                        var val = mdf.Readobject(n);
                        if (val != null)
                            tp.Add(n, val);
                    }
                    if (tp.Count > 0) tps.Add(tp);
                }
            }
            catch (Exception ee)
            {
                //EDs.Msg(ee.Message + "/" + kpath);
            }
            return tps;
        }

        public static List<Dictionary<string, object>> GetRegistryProperties(string kpath, string kname)
        {
            List<Dictionary<string, object>> tps = new List<Dictionary<string, object>>();

            try
            {
                foreach (string sub in GetSubkeys(kpath + "\\" + kname))
                {
                    //EDs.Msg("sub=" + sub);
                    Dictionary<string, object> tp = new Dictionary<string, object>();
                    ModifyRegistry mdf = new ModifyRegistry(kpath + "\\" + kname + "\\" + sub);
                    var names = mdf.Subvalues();
                    //EDs.Msg("names=" + names);

                    foreach (string n in names)
                    {
                        var val = mdf.Readobject(n);
                        if (val != null)
                            tp.Add(n, val);
                    }
                    if (tp.Count > 0) tps.Add(tp);
                }
            }
            catch (Exception ee)
            {
                //EDs.Msg(ee.Message + "/" + kpath + "\\" + kname);
            }
            return tps;
        }

        public static void SetRegistryProperties(this object Pt, string sub)
        {
            ModifyRegistry mdf = new ModifyRegistry(sub);
            foreach (var p in Pt.GetType().GetProperties())
                if (p.GetValue(Pt, null) != null)
                    mdf.Write(p.Name, p.GetValue(Pt, null));
            return;
        }

        public static void SetStrings(string path, List<string> values, int number = 10)
        {
            DeletePath(path);
            if (values.Count == 0) return;

            for (int i = 0; i < Math.Min(values.Count, 10); ++i)
            {
                Set(path, i.ToString("00"), values[i]);
            }
            return;
        }

        public static void DeletePath(string path)
        {
            ModifyRegistry mdf = new ModifyRegistry(path);
            mdf.DeleteSubKeyTree();
        }

        public static List<object> GetValues(string path)
        {
            List<object> gets = new List<object>();

            ModifyRegistry mdf = new ModifyRegistry(path);

            List<string> names = GetNames(path);

            if (names.Count > 0)
            {
                foreach (string s in names)
                {
                    try
                    {
                        gets.Add(mdf.Readobject(s));
                    }
                    catch (System.Exception ee)
                    {
                    }
                }
            }
            return gets;
        }

        public static Dictionary<string, object> GetRegistry(string kpath)
        {
            string sub = kpath;
            //EDs.Msg("sub=" + sub);

            Dictionary<string, object> tp = new Dictionary<string, object>();
            ModifyRegistry mdf = new ModifyRegistry(sub);

            var names = mdf.Subvalues();

            //EDs.Msg("names=" + names);
            //EDs.Msg("names len=" + names.Length);

            if (names != null && names.Length > 0)
            {
                foreach (string n in names)
                {
                    var val = mdf.Readobject(n);
                    if (val != null)
                        tp.Add(n, val);
                }
            }
            //EDs.Msg("tp s: " + string.Join("," , tp.Select(x => x.Key)));

            return tp;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //by lisp.vn
    }
}



3 Sử dụng

Lưu mã sau dưới dạng tệp tin MainWindow.cs
Code:
using lhBasic;
using System.Windows;

namespace AJS_Regs
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public const string kpath = "AJS-Regs.Test";

        public MainWindow()
        {
            InitializeComponent();
        }

        public int IntValue { get; private set; }
        public double doubleValue { get; private set; }
        public bool boolValue { get; private set; }
        public string stringValue { get; private set; } = "Default String";

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IntValue = Regs.Get(kpath, "IntValue", 10);
            doubleValue = Regs.Get(kpath, "doubleValue", 10.0);
            boolValue = Regs.Get(kpath, "boolValue", true);
            stringValue = Regs.Get(kpath, "stringValue", "AJS-Regs");
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Regs.Set(kpath, "IntValue", IntValue);
            Regs.Get(kpath, "doubleValue", doubleValue);
            Regs.Get(kpath, "boolValue", boolValue);
            Regs.Get(kpath, "stringValue", stringValue);
        }
    }
}



---------------------------------------------------------------------------------------------
Ứng dụng được phát triển bởi đội ngũ AutoLISP Thật là đơn giản - Tác giả ứng dụng in D2P

    

Mọi thông tin xin liên hệ Fanpage AutoLISP Thật là đơn giản!
Cảm ơn bạn đã theo dõi!

Không có nhận xét nào:

Đăng nhận xét

Hàm SUMIFS tính tổng theo nhiều điều kiện trong Excel | SUMIFS, COUNTIFS | AutoLISP Reviewer

Hàm SUMIFS tính tổng theo nhiều điều kiện trong Excel Cần tính doanh số của một nhân viên cho một mặt hàng, hay tổng tiền trong một tháng? ...