Create a new class with name CookieHelper.cs In your project and paste the following code.

public class CookieHelper
    {
        #region Constants

        /// <summary>
        /// The cookie name
        /// </summary>
        public const string cookieName = "UserName";

        #endregion

        #region Enums

        public enum EnumCookieInterval
        {
            SECOND = 0,
            MINUTE = 1,
            DAY = 2,
            MONTH = 3,
            YEAR = 4
        };

        #endregion

        #region Utilities

        /// <summary>
        /// Calculates the cookie lifetime.
        /// </summary>
        /// <param name="duration">The duration.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <returns>Expire date for cookie</returns>
        private static DateTime CalculateCookieLifetime(int duration, Enum durationType)
        {
            DateTime cookieExpire = DateTime.Now;

            switch (Convert.ToInt32(durationType))
            {
                case 0:
                    cookieExpire = DateTime.Now.AddSeconds(duration);
                    break;

                case 1:
                    cookieExpire = DateTime.Now.AddMinutes(duration);
                    break;

                case 2:
                    cookieExpire = DateTime.Now.AddDays(duration);
                    break;

                case 3:
                    cookieExpire = DateTime.Now.AddMonths(duration);
                    break;

                case 4:
                    cookieExpire = DateTime.Now.AddYears(duration);
                    break;

                default:
                    cookieExpire = DateTime.Now.AddDays(duration);
                    break;
            }
            return cookieExpire;
        }
        
        #endregion

        #region Methods

        /// <summary>
        /// Creates the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <param name="cookieValue">The cookie value.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        public static string CreateCookie(string cookieName, string cookieValue, Enum durationType, int duration)
        {

            HttpCookie myCookie = new HttpCookie(cookieName);

            // Set the cookie value.
            myCookie.Value = cookieValue;

            // Set the cookie expiration date.
            myCookie.Expires = CalculateCookieLifetime(duration, durationType);

            // Add the cookie.
            //Response.Cookies.Add(myCookie);
            HttpContext.Current.Response.Cookies.Add(myCookie);

            return cookieValue;

        }

        /// <summary>
        /// Reads the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <returns></returns>
        public static string ReadCookie(string cookieName)
        {

            string cookieValue = string.Empty;

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie = HttpContext.Current.Request.Cookies[cookieName];

            // Read the cookie information and display it.
            if (myCookie != null)
                cookieValue = myCookie.Value;


            return cookieValue;
        }

        /// <summary>
        /// Updates the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        /// <param name="cookieValue">The cookie value.</param>
        /// <param name="durationType">Type of the duration.Use enum to specify</param>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        public static string UpdateCookie(string cookieName, string cookieValue, Enum durationType, int duration)
        {

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie = HttpContext.Current.Request.Cookies[cookieName];

            // Set the cookie value.
            myCookie.Value = cookieValue;

            // Set the cookie expiration date.
            myCookie.Expires = CalculateCookieLifetime(duration, durationType);

            // Add the cookie.
            //Response.Cookies.Add(myCookie);
            HttpContext.Current.Response.Cookies.Add(myCookie);

            return cookieValue;

        }

        /// <summary>
        /// Deletes the cookie.
        /// </summary>
        /// <param name="cookieName">Name of the cookie.</param>
        public static void DeleteCookie(string cookieName)
        {
            HttpCookie myCookie = new HttpCookie(cookieName);

            DateTime cookieExpire = DateTime.Now;

            // Set the cookie expiration date.
            myCookie.Expires = cookieExpire.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(myCookie);

        }

        #endregion
    }



How to use?


1. Create cookie 

string cookie = CookieHelper.CreateCookie(CookieHelper.cookieName, "Here is cookie value", CookieHelper.EnumCookieInterval.DAY, 7);

string cookie = CookieHelper.CreateCookie(CookieHelper.cookieName, "Here is cookie value", CookieHelper.EnumCookieInterval.MONTH, 1);

2. Read Cookie

string cookie = CookieHelper.ReadCookie(CookieHelper.cookieName);

3. Update Cookie

string newCookie = CookieHelper.UpdateCookie(CookieHelper.cookieName, "Updated cookie value", CookieHelper.EnumCookieInterval.DAY, 14);

4. Delete Cookie

CookieHelper.DeleteCookie(CookieHelper.cookieName);

Hope it will helps you. Let me know your thoughts!



In almost 90% of projects, we need to upload images to server and store them. In most cases, hackers try to exploit an image upload system and try to upload exploitable materials like webshells, some harmful scripts, table deletions scripts, etc.

To prevent this, I have written one helper function which validates file in many conditions and makes sure the file is in correct image format. The code is not fully written by me, I researched many articles and filtered the conditions which helps us to validate the required output.
        /// <summary>
        /// Verifies that a uploading file is in valid Image format
        /// </summary>
        /// <author>
        /// Mayur Lohite
        /// </author>
        /// <param name="postedFile">File which is selected for upload</param>
        /// <param name="imageMinBytes">Minimum file size in byte</param>
        /// <param name="imageMaxBytes">Maximum file size in byte</param>
        /// <returns>true if the file is a valid image format and false if it's not</returns>
        public static bool IsValidImageFormat(HttpPostedFileBase postedFile, int imageMinBytes, long imageMaxBytes)
        {

            //-------------------------------------------
            //  Check the image extension
            //-------------------------------------------
            if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg"
                && Path.GetExtension(postedFile.FileName).ToLower() != ".png"
                && Path.GetExtension(postedFile.FileName).ToLower() != ".gif"
                && Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg")
            {
                return false;
            }

            //-------------------------------------------
            //  Check the image MIME types
            //-------------------------------------------
            if (postedFile.ContentType.ToLower() != "image/jpg" &&
                        postedFile.ContentType.ToLower() != "image/jpeg" &&
                        postedFile.ContentType.ToLower() != "image/pjpeg" &&
                        postedFile.ContentType.ToLower() != "image/gif" &&
                        postedFile.ContentType.ToLower() != "image/x-png" &&
                        postedFile.ContentType.ToLower() != "image/png")
            {
                return false;
            }



            //-------------------------------------------
            //  Attempt to read the file and check the first bytes
            //-------------------------------------------
            try
            {
                if (!postedFile.InputStream.CanRead)
                {
                    return false;
                }

                if (postedFile.ContentLength < imageMinBytes)
                {
                    return false;
                }

                if (postedFile.ContentLength < imageMinBytes)
                {
                    return false;
                }

                byte[] buffer = new byte[512];
                postedFile.InputStream.Read(buffer, 0, 512);
                string content = System.Text.Encoding.UTF8.GetString(buffer);
                if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
                    RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }

            //-------------------------------------------
            //  Try to instantiate new Bitmap, if .NET will throw exception
            //  we can assume that it's not a valid image
            //-------------------------------------------

            try
            {
                using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream))
                {
                }
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }


Hope it will help you. Let me know your thoughts!