12 Jul

Empty The Recycle Bin Using C#

This example shows how to empty the recycle bin using C#. First we will need to define the following function that will be empty the recycle bin:

        [DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
        static extern uint SHEmptyRecycleBin (IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);
        
        public enum RecycleFlags : uint
        {
            SHERB_NOCONFIRMATION = 0x00000001,
            SHERB_NOPROGRESSUI = 0x00000002,
            SHERB_NOSOUND = 0x00000004
        }

Usage:

uint result = SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHERB_NOCONFIRMATION);
12 Jul

C# Open And Close CD Drive Tray

This example shows how to open and close the tray of the CD drive. First we will need to define the following function that will be opening the disk tray:

        [DllImport("winmm.dll", EntryPoint = "mciSendString")]
        public static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

Usage:

            //To open
            int result = mciSendString("set cdaudio door open", null, 0, 0);

            //To close
            result = mciSendString("set cdaudio door closed", null, 0, 0);
12 Jul

C# Read And Write A Registry Key

This example shows how to read and write a registry key. To do this, we must use RegistryKey and Registry classes in Microsoft.Win32 namespace.

Usage:

            //Usage:
            Write("REGISTRY DATA1", "http://www.csharpexamples.com");
            Write("REGISTRY DATA2", 123.ToString());

            string registryData1 = Read("REGISTRY DATA1");
            string registryData2 = Read("REGISTRY DATA2");

Sample Read and Write Methods:

        /// 
        /// This C# code reads a key from the windows registry.
        /// 
        /// 
        /// 
        public string Read(string keyName)
        {
            string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();

            RegistryKey sk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(subKey);
            if (sk == null)
                return null;
            else
                return sk.GetValue(keyName.ToUpper()).ToString();
        }

        /// 
        /// This C# code writes a key to the windows registry.
        /// 
        /// 
        /// 
        public void Write(string keyName, string value)
        {
            string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();

            RegistryKey sk1 = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(subKey);
            sk1.SetValue(keyName.ToUpper(), value);
        }