开发者

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.开发者_Go百科Exists)
{
 FileInfo file2 = new FileInfo(destFile);
 if (!file2.Exists)
 {
  try
  {
   File.Move(srcFile, destFile);
  }
  catch (System.IO.IOException e)
  {
   Console.WriteLine(e.Message);
  }
}
}


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.


Are you creating or opening file1 from within your code? If so, you'll need to close the FileStream before attempting the move.


Check with process explorer which process holds the file open.


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


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.


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜