Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are cookies in C#?

Adeyemi Tubosun

Cookies are small units of information that follow all request processes and web pages as they travel between Web browsers and servers.

The above definition implies that every web page opened on a website has an exchange of cookies between the server and the web pages. If a User registers an account and wants to log in, they will be asked whether or not they wish to save their username and password. The next time they’re using the website, the username and the password will be read directly from the cookies.

Types of cookies

  1. Persistent cookie

  2. Non-Persistent cookies

1). Persistent cookies

Once cookies are generated, they will test time before expiration, depending on the issuer’s specification. This type of cookie is not only active when the user is active on the website; it can track what the user does over multiple websites with links.

2).Non-persistent cookies

Cookies are saved temporarily on the User’s memory; this cookie is created when the user is available and gets deleted when the user exits the web browser.

Operations on cookies

• Write (save) values in cookies

• Read values stored in cookies

• Remove (delete) cookies


Let’s take a look at how we can write cookies:

protected void Button1_Click(object sender, EventArgs e)  
    //create a cookie by using HttpCookie class and add the name of the cookie that is Democookie  
    HttpCookie cookie = new HttpCookie("Democookie");  
    //assign the textBoxes Value on introduction-of-cookies  
    cookie["UserName"] = tbUserName.Text;  
    cookie["Pwd"] = tbPwd.Text;  
    //Write the Cookies on the client machine  
   //Redirect the page to other page  


Let’s take a look at how we can read cookies:

protected void Page_Load(object sender, EventArgs e)  
    //Retrive the Demointroduction-of-cookies on the client's pc  
    HttpCookie cookie = Request.Cookies["Democookie"];  
   if (cookie != null)  
       //assign the introduction-of-cookies value on the labelk  
      lblUname.Text = cookie["UserName"];  
      LblPwd.Text = cookie["Pwd"];  


It is vital to know that while cookies play very significant roles in all web-related activities, we must also watch out for substantial threats they pose to us, especially in areas of security. In cases of security loopholes, cookies can be hijacked by internet fraudsters to mess up a User’s account.



View all Courses

Keep Exploring