Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.Move fails when preceded by a File.Delete

Tags:

c#

io

We have a MoveFile method which usually work, but keep failing at a customer site.

if (File.Exists(target))
{
    File.Delete(target);
}

File.Move(source, target);

The call to File.Move fails repeatedly with

System.IO.IOException: Cannot create a file when that file already exists.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.__Error.WinIOError()
   at System.IO.File.Move(String sourceFileName, String destFileName)

We have error handling surrounding call to that method, but we can't figure out why File.Delete is not working and is not throwing anything.

We though about file permission, but then the File.Delete would have throw an UnauthorizedAccessException.

Are there any other reason that would make File.Move fail with a "file already exist" when it is preceded by the deletion of that specific file?

like image 541
Pierre-Alain Vigeant Avatar asked Apr 18 '11 15:04

Pierre-Alain Vigeant


People also ask

Does file move delete?

Moving – move the original files or folder from one place to another (change the destination). The move deletes the original file or folder, while copy creates a duplicate.

Does file move overwrite?

Move(String, String, Boolean) Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.


2 Answers

Can you reverse the logic?

File.Copy (source, target, true) 

to overwrite the target then

File.Delete(source)
like image 100
MarcE Avatar answered Nov 02 '22 23:11

MarcE


In the past, I've found that the system tends to delete the file "slower" than your program is running.

Ideally you need to check whether the file has been deleted, before trying to then move a file into its place. Usually you can get round this with a simple Thread.Sleep(200) or similar, but it's probably not the most reliable way!

like image 4
Daniel Frear Avatar answered Nov 02 '22 22:11

Daniel Frear