2

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?

Jake
  • 3,142
  • 4
  • 30
  • 48

3 Answers3

3

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)

Community
  • 1
  • 1
Daniel Mošmondor
  • 19,718
  • 12
  • 58
  • 99
  • So basically, a good strategy might be to make a function which does the following: If (folder does not exist) -> just use .move If (folder does exist) -> run the function on each subdirectory That way I can recursively rename every directory and subdirectory, and if they already exist, just move the stuff within. Is that right? – Jake Jun 15 '12 at 16:48
  • Heh well that's far easier! Thanks! – Jake Jun 15 '12 at 16:51
0

I would do it this way:

if(Directory.Exists(destinationPath))
{
    Directory.Delete(destionatPath, true /* recusively nuke everything */ );
}

Directory.Move(sourcePath, destinationPath);
bluevector
  • 3,485
  • 1
  • 15
  • 18
0

You cannot use the Directory.Move method to move the files into an existing folders. You have to move the files manually in this case using a foreach loop on file level for example. Directory.Move only works if the destination directory does not exit. You could however check if the directory already exists or try it and handle the IOException exception so that you do the foreach only if necessary.

Jason De Oliveira
  • 1,732
  • 9
  • 16