Exceptions and FileInfo.MoveTo

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
 
W

William Ryan

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top