How to create cookie in VB.Net & C#

Cookie is  one of the useful object that can be used in the web application, and you can use it to save user setting on the local computer or device.

 Before create any Cookie please read these hints:
1. This part was copied directly from Cookie Law :
  Cookie laws have changed with effect from 26th May 2011.
On 26th May 2011, new laws came into force in the UK that affect most web sites. If cookies are used in a site, the Privacy and Electronic Communications (EC Directive) (Amendment) Regulations 2011 (UK Regulations) provide that certain information must be given to that site’s visitors and the user must give his or her consent to the placing of the cookies…..
For further information please go to  the Cookie Law
2. Programmers have not to save sensitive(confidential) information same as Username, Password, Credit card number or something like that in the Cookies.
Seat your belt we want to finish this part rapidly 🙂
Different parts of Cookies:
 1. Name: each Cookie must has the specific name.
2. Value: Each Cookie has specific value, without value Cookie does not have meaning.
3 Expire Date: .Each Cookie must have Expire date, we do not want to save a Cookie for ever!
Before you create a Cookie must check the Cookie existent, if the Cookie already is exits no need to create it again, you just have to update the value or Expire date.

 Private Sub CreateCookies()

        If Request.Cookies("UserName") Is Nothing Then

            Dim aCookie As New HttpCookie("UserName")

            aCookie.Value = "MyUsername"

            aCookie.Expires = DateTime.Now.AddDays(30)



            Dim cookie As HttpCookie = HttpContext.Current.Request.Cookies("UserName")

            cookie.Value = "UserName"

            cookie.Expires = DateTime.Now.AddDays(30)


        End If



private void CreateCookies()


    if (Request.Cookies("UserName") == null) {

        HttpCookie aCookie = new HttpCookie("UserName");

        aCookie.Value = "MyUsername";

        aCookie.Expires = DateTime.Now.AddDays(30);


    } else {

        HttpCookie cookie = HttpContext.Current.Request.Cookies("UserName");

        cookie.Value = "UserName";

        cookie.Expires = DateTime.Now.AddDays(30);






2 thoughts on “How to create cookie in VB.Net & C#”

  1. I’m impressed, I must say. Really rarely do I encounter a blog that’s both educative and entertaining, and let me tell you, you have hit the nail on the head. Your idea is outstanding; the issue is something that not enough people are speaking intelligently about. I am very happy that I stumbled across this in my search for something relating to this.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s