It depends on how you opened the file. Most likely,
you forgot to dispose something. The disposal mechanism usually takes care of certain things you need to clean up in a controlled manner (in contrast to, say,
Garbage Collector functionality), in some point of execution of your code; and some typical uses of it are cleaning up unmanaged resources and — what a surprise! — closing of file handles.
Basically, you need to watch yourself of using of any types implementing
System.IDisposable
and call
System.IDisposable.Dispose
in the appropriate points. Please see:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[
^].
It's important to makes sure this call is done even if exception is thrown, via a try-finally statement. The best fool-proof way of doing it is using the
using
statement (don't mix it up with
using
clause!). Please see:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[
^].
Let's consider a simple example. When you open a file with
System.IO.StreamReader
, you do it in the exclusive-use mode (which is the best thing to do anyway). You won't be able to read the same file in parallel until the instance of the reader is disposed:
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
string line = reader.ReadLine();
}
You could have used different ways of accessing your files, you could get read, write, read/write access, work on lower levels of file or stream interfaces, etc., but the principle is the same.
[EDIT]
By the way, when you need an information of a process holding your file, you can use the
Sysinternal's utility "
handle.exe". Please see my recent answer for further detail:
Pause the use of a file by a process?[
^].
—SA