I am trying to move the directory from one location to another location on the same drive. I am getting "Cannot create a file when that file already exists" error. Below is my code.
could any one suggest on this?
string sourcedirectory = @"F:\source"; string destinationdirectory = @"F:\destination"; try { if (Directory.Exists(sourcedirectory)) { if (Directory.Exists(destinationdirectory)) { Directory.Move(sourcedirectory, destinationdirectory); } else { Directory.CreateDirectory(destinationdirectory); Directory.Move(sourcedirectory, destinationdirectory); } } } catch (Exception ex) { log(ex.message); }
Press Windows key + R to open up a Run dialog box. Then, type ms-settings:windowsupdate and press Enter to open up the Windows Update tab inside the Settings app. Run dialog: ms-settings:windowsupdate. Inside the Windows Update screen, click on Check for updates and install every available pending update.
The error message "File Already Exists" or "File Already in Use" indicates that a file CTI Navigator Desktop is attempting to use is already open, locked or corrupted. The fix is to replace a corrupted file, and close, unlock or replace a locked file.
File. Move() doesn't support overwriting of an existing file. In fact, it will throw an IOException if a file with the same path as sourceDestFilename already exists.
As both of the previous answers pointed out, the destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
Something like this:
class Program { static void Main(string[] args) { string sourcedirectory = @"C:\source"; string destinationdirectory = @"C:\destination"; string backupdirectory = @"C:\Backup"; try { if (Directory.Exists(sourcedirectory)) { if (Directory.Exists(destinationdirectory)) { //Directory.Delete(destinationdirectory); Directory.Move(destinationdirectory, backupdirectory + DateTime.Now.ToString("_MMMdd_yyyy_HHmmss")); Directory.Move(sourcedirectory, destinationdirectory); } else { Directory.Move(sourcedirectory, destinationdirectory); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } }
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