Remove all session keys except one

  • Thread starter Thread starter Fredrik Rodin
  • Start date Start date
F

Fredrik Rodin

Hi!

I want to basicaööy run a Session.Abandon() on logout but keep one session.
In order to do this I'm iterating through my session collection by runing
the follwoing code:

Dim iSessionCount As Integer = Session.Count - 1

For i As Integer = 0 To iSessionCount

If Session.Contents.Keys(i) <> "ReturnPath" Then

Session.Remove(Session.Keys(i))

End If

Next

The statement works fine, but since I use the remove-statement, the index
decrease by 1 for each session I remove. So, let's say I have 5 sessions. i
run my code and iSessionCount will be 4 all through the loop. BUT, after the
first removal, the session index count will be 3. As a result of this I will
end up in an out-of-index error message.

Any ideas? I've been googling around but can only find solutions for the
Classic ASP-world and I want to do it the .NET-way.

Any help is appreciated.

Thanks in advacne,
Fred
 
Fred,
I think you're making this one too complicated. Instead of starting
at zero, why not start at the last session and work your way back down to
zero. That way you're always popping the last one off.

Hope this helps,
Mark Fitzpatrick
Microsoft MVP - FrontPage
 
The usual trick is to browse the collection starting by the end :

For i=Session.Count-1 to 0 step -1
If ...
Next


Patrice
 
Thanks to Mark Fitzpatrick and Patrice!

It did solve my problem to reverse the loop.

Thanks,
Fred
 
You could also set the session variable to a temporary value, clear the session, then reset it, such as

object returnPath = Session["ReturnPath"

Session.Clear(
Session.Abandon(

Session["ReturnPath"] = returnPath
 
Back
Top