Let’s say I have Directory 1 and Directory 2, and each can have files or subdirectories within them. What I have so far is, if I want to rename “Directory 2” to “Directory 3”, I can run:
Directory.Move("path\Directory 2", "path\Directory 3");
This works fine – renames the directory, all subdirectories and files within that directory work fine with the new name, no copies to deal with.
However, if I try to do this:
Directory.Move("path\Directory 2", "path\Directory 1");
I get an error, because Directory 1 already exists. In that case, should Directory 2 not be able to be renamed to Directory 1, all contents (files and subdirectories) in Directory 2 should just get moved into Directory 1. What’s the easiest way to do this? Should I have an if file exists, a foreach to move all subdirectories, and a foreach to move all files? Is there an easier way to overload the .Move function to move the files regardless of existence errors?
No, since MOVE works on file system level, effectively renaming a folder, or moving folder “pointer” to another place. Former is the case when parent directories are the same, and latter when parent directories differ.
So in answer to your direct question, you’ll have to foreach each child directory in case when target exists and has something in it. If it doesn’t, you can always erase it and go with MOVE-ing.
Look here: Directory.Move doesn't work (file already exist)