fokz8 fokz8 - 1 month ago 12
ASP.NET (C#) Question

How to cut string size in c# asp.net

I want to save multiple string values in one cookie, with strings that are larger than 4kb cut to 1.3kb

This is my code - notice - im not sure code is working correctly, since no cookies show when i try to display them in textboxes, not sure why.

EDIT - save cookies

protected void btnCookie_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("cookie");
cookie.Values.Add("cookie1", txtValue1.Text);
cookie.Values.Add("cookie2", txtValue2.Text);
cookie.Values.Add("cookie3", txtValue3.Text);

cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
Response.Write("Success!");
}


read cookies

protected void btnLoadCookies_Click(object sender, EventArgs e)
{
if ((Request.Cookies["cookie"] != null))
{
TextBox1.Text = Request.Cookies["cookie"]["cookie1"];
TextBox2.Text = Request.Cookies["cookie"]["cookie2"];
TextBox3.Text = Request.Cookies["cookie"]["cookie3"];
}
}


Can you guys please help me create a function/code that would cut string size from 4kb to 1.3kb ?

Thank you!

Answer

You weren't adding the cookie:

    HttpCookie cookie = new HttpCookie("cookie");
    cookie.Values.Add("cookie1", txtValue1.Text);
    cookie.Values.Add("cookie2", txtValue2.Text);
    cookie.Values.Add("cookie3", txtValue3.Text);

    //  Now tell the Response about it
    Response.Cookies.Add(cookie);

Sorry to be such a royal pain in comments, but you ended up basically figuring it out yourself.

If you do end up needing to truncate the text, you want String.Substring(). But you can also give yourself more breathing room by saving three 4k chunks of text in three different cookies rather than three properties of one cookie.