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?
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.
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.
Can you reverse the logic?
File.Copy (source, target, true)
to overwrite the target then
File.Delete(source)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With