Reputation: 241
I have a problem with deleting session variables..
Assume I have 30 session variables...I want to delete 29 session variables but one.How can I do this please help me!
I tried Session.RemoveAll() With this it deletes ALL the sessions.But my required requirement is to delete all but ONE Session.How do i do it?
Upvotes: 1
Views: 1736
Reputation: 17604
You can use Session.Remove
to remove using key
from the session collection.
You can loop through you session collection
for (int i = 0; i < Session.Contents.Count; i++)
{
var key = Session.Keys[i];
var value = Session[i];
//remove the key except one
if(key!="youkey")
Session.Remove(key);
}
As suggested by @JoachimIsaksson
for (int i = 0; i < Session.Contents.Count; i++)
{
var key = Session.Keys[i];
var value = Session[i];
//remove the key except one
if(key!="youkey")
{
Session.Remove(key);
i++;
}
}
As suggested by @JoachimIsaksson I am not sure right one or not
for (int i = 0; i < Session.Contents.Count; i++)
{
var key = Session.Keys[i];
var value = Session[i];
//remove the key except one
if(key!="youkey")
{
Session.Remove(key);
i--;
}
}
Upvotes: 4
Reputation: 181077
You could just simply save the variable you want to keep, clear all and put it back;
var value = Session["tokeep"];
Session.RemoveAll();
Session["tokeep"] = value;
Upvotes: 1