14 Jul

C# Compare Dates

This example shows how to compare dates using C#.

Usage 1:

            DateTime dateTime1 = DateTime.Parse("05/05/2009");
            DateTime dateTime2 = DateTime.Now;
            if (dateTime1.Date > dateTime2.Date)
            {
                //It's later date
            }
            else
            {
                //It's earlier or equal date
            }

Usage 2:

            int result = DateTime.Compare(dateTime1, dateTime2);
            if (result < 0)
            {
                //it is earlier
            }
            else if (result == 0)
            {
                //it is the same time as
            }
            else
            {
                //it is later
            }
13 Jul

C# Create A MD5 Hash From A String

This example shows how to create a MD5 hash from a string.

Usage:

            string hash = CreateMD5Hash("http://www.csharpexamples.com");
            Console.WriteLine(hash);
            //Output: 
            //E426A83F137FA324C3412B92193EED1F
        public string CreateMD5Hash(string input)
        {
            // Step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            
            // Step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }
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);