How can one test if a file is in use?

For example, the following code:

//Start Code Fragment
string sourceFile = "some source file path";
string targetFile = "some target file path";
FileInfo fi1 = new FileInfo(targetFile);
try
{
fi1.MoveTo(targetFile);
}
catch (Exception e)
{
Console.WriteLine("Unable to move the file: {0}", e.ToString());
}
//End Code Fragment

Throws the following exception:

//Start Exception
Unable to move the file: System.IO.IOException: The process cannot access
the fi
le because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String str)
at System.IO.__Error.WinIOError()
//End Exception

Is it possible to test if a file is in use without trying to move it? I
can't seem to find anything.

thanks
ricky

Re: Exceptions and FileInfo.MoveTo by William

William
Mon Sep 15 10:42:18 CDT 2003

I don't think there is. There's no attribute per se 'in use' but you can
try catch an open or move and deduce it from there. I don' think there's
anytime more elegant.

HTH,

Bill
"Richard Hensh" <henshr@rgsgroup.com> wrote in message
news:ed3UB51eDHA.1872@TK2MSFTNGP09.phx.gbl...
> How can one test if a file is in use?
>
> For example, the following code:
>
> //Start Code Fragment
> string sourceFile = "some source file path";
> string targetFile = "some target file path";
> FileInfo fi1 = new FileInfo(targetFile);
> try
> {
> fi1.MoveTo(targetFile);
> }
> catch (Exception e)
> {
> Console.WriteLine("Unable to move the file: {0}", e.ToString());
> }
> //End Code Fragment
>
> Throws the following exception:
>
> //Start Exception
> Unable to move the file: System.IO.IOException: The process cannot access
> the fi
> le because it is being used by another process.
> at System.IO.__Error.WinIOError(Int32 errorCode, String str)
> at System.IO.__Error.WinIOError()
> //End Exception
>
> Is it possible to test if a file is in use without trying to move it? I
> can't seem to find anything.
>
> thanks
> ricky
>
>