Exceptions and FileInfo.MoveTo

  • Thread starter Thread starter Richard Hensh
  • Start date Start date
R

Richard Hensh

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
 
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
 
Back
Top