Using a while loop arround the code open and write to the file.
Suggestion, put that code into another thread, so if it can't write out yet. Just sleep for one sec and try again. Something like this could do a dirty trick;
writtenOut = false;
if could open file
write to file
You should only get the some other process is using that file if you're trying to open it, so as other have said open it, dont close it until you're done with it. Then there is no major delay to writing the file.
so as other have said open it, dont close it until you're done with it
I'd not recommend this in practice. If you open it and just hold on to it, what other process is now failing because you're holding onto resources? How about doing some research to find out what other process is using the file? If it's your own code doing it, then there's probably a bug in there somewhere of not releasing it properly that needs to be corrected. I'd look at something like HandleEx from sysinternals to determine what is holding onto the file.