Bi.
Bi.

Reputation: 1906

File.Move error in C#

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

Answers (7)

user339140
user339140

Reputation: 1

maybe open the file1 in your code before you move it and don't close the filestream

Upvotes: 0

Polyfun
Polyfun

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

Neil Knight
Neil Knight

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

hakan
hakan

Reputation: 906

Use Unlocker to see file locks. It will help you to figure out the problem.

http://www.emptyloop.com/unlocker/

Upvotes: 0

Midhat
Midhat

Reputation: 17840

Use procmon to find out which process is using the file and handle the situation.

Upvotes: 2

Marek
Marek

Reputation: 10402

Check with process explorer which process holds the file open.

Upvotes: 3

Oded
Oded

Reputation: 499312

The error means that the file is in use:

  • either by your application (you need to close the file in order to be able to move it)
  • or by another application. There isn't much you can do here, but retry later.

Upvotes: 4

Related Questions