How to create and Retrieve the cookies in C# and ASP.net

Cookies are Client side State management, it is a small text file created by web application in browser memory to store some temporary values. Cookies occupies 4kb of browser memory to store the values.There are two types of cookies

Persistence Cookie (cookies created with the expiration time)
Non-Persistence Cookie (cookies created without the expiration time, expires automatically when browser is closed)

In real time you can notice the usage of cookies in your Gmail, Live mail and other accounts with ‘Remember password’ option, here even after the browser is closed, visiting the same site again, It won’t ask you to login again. This functionality is purely because of cookies.
In the below code, in page load event am checking the cookie value, if exists it will be shown in label. Else create the cookie value by entering the value in textbox and click the ‘create cookie’ button.


ASP.NET CODE

<html>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td><asp:TextBox ID="txt_login" runat="server"></asp:TextBox></td>
    <td><asp:Button ID="btn_cookie" runat="server" Text="Create Cookie"
            onclick="btn_cookie_Click" /></td>
    </tr>
    <tr>
    <td><asp:Label ID="lbl_cookie_value" runat="server"></asp:Label></td>
    <td></td>
    </tr>
    </table>
    <br />
    </div>
    </form>
</body>
</html>

C# CODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AppCookie
{
    public partial class Page1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //check cookie exists or not
            HttpCookie cook = new HttpCookie("testcook");
            cook = Request.Cookies["CookName"];
            if (cook != null)
            {
                lbl_cookie_value.Text = cook.Value;
            }
            else
            {
                lbl_cookie_value.Text = "Empty value";
            }
        }
        
        protected void btn_cookie_Click(object sender, EventArgs e)
        {
            //create cookie with some ID as i have given CookName
            HttpCookie myCookieobj = new HttpCookie("CookName");
            myCookieobj.Value = txt_login.Text.ToString();
            myCookieobj.Expires = DateTime.Now.Add(TimeSpan.FromHours(200));
            Response.Cookies.Add(myCookieobj);
        }

    }
}


By : Divya Satharasi