tags:

views:

305

answers:

3

I've got main folder:

c:\test

And there I have 2 folders: Movies and Photos.

Photos has three folders with files with the same structure: People, Animals and Buildings. I'm trying this code:

Directory.Move(@"c:\test\Movies", @"c:\test\Test");

I get exception:

File already exists
+4  A: 

The destination directory should not already exist - the Directory.Move method creates the destination directory for you.

Fiona Holder
A: 

Is it safe for you to delete the destination folder before copying new contents to it?

    Directory.Delete(@"c:\test\test");
    Directory.Move(@"c:\test\movies",@"c:\test\test");
cptScarlet
Unfortunalety not...
+1  A: 

This method will move content of a folder recursively and overwrite existing files.
You should add some exception handling.
Edit:
This method is implemented with a while loop and a stack instead of recursion.

public static void MoveDirectory(string source, string target)
{
    var stack = new Stack();
    stack.Push(new Folders(source, target));

    while (stack.Count > 0)
    {
        var folders = stack.Pop();
        Directory.CreateDirectory(folders.Target);
        foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
        {
             string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
             if (File.Exists(targetFile)) File.Delete(targetFile);
             File.Move(file, targetFile);
        }

        foreach (var folder in Directory.GetDirectories(folders.Source))
        {
            stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
        }
    }
    Directory.Delete(source, true);
}
public class Folders
{
    public string Source { get; private set; }
    public string Target { get; private set; }

    public Folders(string source, string target)
    {
        Source = source;
        Target = target;
    }
}
Jens Granlund