I have an integration/regression test suite I built on top of SpecFlow (which uses NUnit underneath). The problem I am having is that sometimes there is an exception in a test and a file might remain open. This is a problem in follow on tests because they cannot read/write to this file.
Is there a way to detect what files a process has open and then close them all?
You should close the handles by either disposing them(best done with the
usingclause) or waiting for the finalizer. Finalizers probably won’t work well for you since they might not run before the next test. So disposing them with eithertry…finallyorusingis the way to go.While you can enumerate handles and close them, you should not. Since then the handle might be closed twice, which will cause undefined behavior and crashes.
Here is some Delphi sample code enumerating all handles of a process which you can filter down to file handles only: