Normally, you are entitled to get your security deposit back within 14 days of when you move out. Foreclosure is not normal because during the foreclosure process the title owner of the property can change, and the foreclosing bank has the right to send tenants a notice to leave. So there is no sure way of getting your deposit back.
Ask your landlord for your security deposit back when you learn of the foreclosure. Keep it in a separate account. After foreclosure, if there is a new owner asking for a security deposit you can give it to them.
If your landlord refuses to give you the security deposit, write a letter to the court asking for an order that the landlord selling the property put the security deposit into a special account that will be transferred to the buyer after sale of the building. Send a copy of your letter to all the parties to the foreclosure action.