Reputation: 1906
I am trying a simple move as shown below and get the following error: "The process cannot access the file because it is being used by another process." How do I fix this? Thanks.
FileInfo file1 = new FileInfo(srcFile);
if (file1.Exists)
{
FileInfo file2 = new FileInfo(destFile);
if (!file2.Exists)
{
try
{
File.Move(srcFile, destFile);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}
}
Upvotes: 1
Views: 6907
Reputation: 1
maybe open the file1 in your code before you move it and don't close the filestream
Upvotes: 0
Reputation: 9639
When you catch this exception, you can try calling the Windows API MoveFileEx, with the MOVEFILE_DELAY_UNTIL_REBOOT flag. This will move the file the next time you reboot; this is want installers normally do when they detect a locked file. You need to be admin or LocalSystem for this to work.
Upvotes: 1
Reputation: 48587
Are you creating or opening file1 from within your code? If so, you'll need to close the FileStream before attempting the move.
Upvotes: 3
Reputation: 906
Use Unlocker to see file locks. It will help you to figure out the problem.
http://www.emptyloop.com/unlocker/
Upvotes: 0
Reputation: 17840
Use procmon to find out which process is using the file and handle the situation.
Upvotes: 2
Reputation: 499312
The error means that the file is in use:
Upvotes: 4