The problem "file is being used by another process" is not related to garbage collection.
As the similar question was asked here many times, from this experience I know: in most cases the blocking process is your own process. You could have forgotten to dispose/close something in the same application. So, first of all, check it up. To explore this possibility, please see my past answer:
Clearing a Handle in C#[
^].
In this answer, pay attention for the using of the
using
statement which helps you to guarantee that appropriate file system object is properly disposed after use, not keeping the file locked.
In same cases, you really need to investigate which process holds which file. For this, I recommend using one utility from the
Sysinternals Suite. This set of utilities (formerly from
Winternals company, presently at Microsoft) is a must-have for any developer, please see:
http://technet.microsoft.com/en-us/sysinternals/bb842062[
^],
http://technet.microsoft.com/en-us/sysinternals/bb545027[
^].
The utility you need is "
handle.exe", please see:
http://technet.microsoft.com/en-us/sysinternals/bb896655[
^].
In your case, you use it with file name parameter:
handle.exe <file_name>
This utility will scan all kinds of handles, not just file handles. For file, it will scan all file handles matching the file name (so it does not have to be a full path name) and return information sufficient to identify each process, including its
pid. So, if you need more information on a process in question, you can also use other Sysinternals utilities, in particular, its
Process Explorer:
http://technet.microsoft.com/en-us/sysinternals/bb896653[
^].
[EDIT]
I mentioned pid above, because you can use it to terminate offending process using
System.Diagnostics.Process.Kill
, but I would not advice you to do so — this is quite unsafe.
Good luck,
—SA