Resource.SaveTo method sometimes temporarily still keeps file in use even after it returns.
I am experiencing this behavior in different solutions.
One of them being in dotNetInstaller (see
The other solution makes a call to EndUpdateResource as well and have noticed that sometimes the file is still in use even after EndUpdateResource returns.
As noted in the dotNetInstaller post, I am thinking that the managed garbage collector has not yet freed open handles\resources from making those windows api calls through pinvoke.
I am thinking that we may need to explicitly call GC.Collect() or wait until the file is no longer in use.
In my code, if I loop while checking if the file is not in use and sleep for 1 second, with a maximum of 5 tries, things work as expected.
This is just a work-around for the time being and is not the best solution I know.
I am not sure how a unit test can be written that can be used to test the unexpected behavior and correct functionality consistently and accurately.
Here is a code snippet for FileInUse mostly borrowed from
public static bool FileInUse(string path)
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
//If required we can check for read/write by using fs.CanRead or fs.CanWrite