Remove all session keys except one

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
 
M

Mark Fitzpatrick

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
 
P

Patrice

The usual trick is to browse the collection starting by the end :

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


Patrice
 
F

Fredrik Rodin

Thanks to Mark Fitzpatrick and Patrice!

It did solve my problem to reverse the loop.

Thanks,
Fred
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top