Read and Write to the Windows Registry - CSharp System

CSharp examples for System:Windows

Description

Read and Write to the Windows Registry

Demo Code


using System;// www  .j ava 2  s  .c  om
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