Asp.net How To Write a Cookie and Read

Asp.net How To Write a Cookie and Read

How to Read and Write cookie in Asp.net. You can store user specific data at client side using cookies. Here we will see how to Read and write cookies in Asp.net. Do not store sensitive information like password or credit card numbers in cookies. You can store other information cookie like login user name, preferences, font size, user preferred themes etc.

You can maintain the data across the web pages using cookie at client side. When user requests the page, browser sends cookie information related to domain or page for that user.

Asp.net C# write cookie example.

Here we will create cookie named User using Asp.net C#. Http Cookie instance will be passed to response of web page. The instance UserNameCookie holds name and value pair, in our example we are setting name of cookie as “UserName” and Value as “Satalaj”.

C# Cookie example.

protected void Page_Load(object sender, EventArgs e)
{

HttpCookie UserNameCookie = new HttpCookie("UserName");
UserNameCookie.Value = "Satalaj";

Response.Cookies.Add(UserNameCookie);

}

VB.net cookie example.

Protected Sub Page_Load(sender As Object, e As EventArgs)

Dim UserNameCookie As New HttpCookie("UserName")
UserNameCookie.Value = "Satalaj"

Response.Cookies.Add(UserNameCookie)

End Sub

Asp.net Read Cookie Example.

To Read Cookie in Asp.net, access cookie information stored inside request. Let's see example.

C# Read Cookie.

protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.Cookies["UserName"].Value;

Response.Write("Retrived user name from cookie is: " + username);
}

VB.net Read Cookie.

Protected Sub Page_Load(sender As Object, e As EventArgs)

Dim UserNameCookie As New HttpCookie("UserName")
UserNameCookie.Value = "Satalaj"

Response.Cookies.Add(UserNameCookie)

End Sub

Summery: We have used instance of HttpCookie to read and write cookie. To write cookie we have added name and value of cookie to HttpCookie instance and passed to Response. To retrieve value from cookie, we used Request object.

Tags:

Asp.net How To Write a Cookie and ReadRead Write MemoryStreamAsp.net How To Remove CookieC# XML XmlReaderAsp.net page specific cookieASP.net read email hotmailAsp.net How To Expire a CookieASP net Write Text On Image C#.net and Vb.net programC# Read File Line By Lineasp net image upload(c#) write to text file

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.