Read and Write to the Windows Registry - CSharp Operating System

CSharp examples for Operating System:Windows

Description

Read and Write to the Windows Registry

Demo Code


using System;//from   w  ww. ja  v a  2  s . c o m
using Microsoft.Win32;

class MainClass
    {
        public static void Main(String[] args)
        {
            string lastUser;
            string lastRun;
            int runCount;

            lastUser = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\book2s.com\csharp tutorial","", "Nobody");

            if (lastUser == null)
            {
                lastUser = "Nobody";
                lastRun = "Never";
                runCount = 0;
            }
            else
            {
                lastRun = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\book2s.com\csharp tutorial","LastRun", "Never");

                runCount = (Int32)Registry.GetValue(@"HKEY_CURRENT_USER\Software\book2s.com\csharp tutorial","RunCount", 0);
            }

            Console.WriteLine("Last user name: " + lastUser);
            Console.WriteLine("Last run date/time: " + lastRun);
            Console.WriteLine("Previous executions: " + runCount);

            Registry.SetValue(@"HKEY_CURRENT_USER\Software\book2s.com\csharp tutorial","", Environment.UserName, RegistryValueKind.String);

            Registry.SetValue(@"HKEY_CURRENT_USER\Software\book2s.com\csharp tutorial","LastRun", DateTime.Now.ToString(), RegistryValueKind.String);

            Registry.SetValue(@"HKEY_CURRENT_USER\Software\book2s.com\csharp tutorial","RunCount", ++runCount, RegistryValueKind.DWord);

        }
    }

Result


Related Tutorials