简体   繁体   中英

Close all open files handles with C#

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?

您应该将文件放在using块中,以便即使引发异常也可以将其关闭。

You should close the handles by either disposing them(best done with the using clause) 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 either try ... finally or using is 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 sample code enumerating all handles of a process: http://nopaste.info/58d1aed48f.html You can filter them down to file handles only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM