Home > Net >  How do I move all subfolders in one directory to another folder in c#?
How do I move all subfolders in one directory to another folder in c#?

Time:10-31

I have a directory with folders and files, and I want to move all the folders into another folder that's inside the directory.

I already can move all the files in the directory(Not including the files in the subfolders), but I am also trying to figure out how to move the subfolders.

string selectedDrive = comboBox1.SelectedItem.ToString();

            string folderName = selectedDrive   @"\\Encrypted"; // Creates a directory under the selected drive.

            System.IO.Directory.CreateDirectory(folderName);
            string moveTo = (selectedDrive   @"\Encrypted");
            String [] allFolders = Directory.GetDirectories(selectedDrive); //Should return folder 

            foreach (String Folder in allFolders)
            {
                if (!Directory.Exists(moveTo   Folder))
                {
                    FileSystem.CopyDirectory(Folder, moveTo);
                }

            }

Instead, I have an error at this line FileSystem.CopyDirectory(Folder, moveTo); saying the following: System.IO.IOException: 'Could not complete operation since source directory and target directory are the same.'

CodePudding user response:

I have reworked your code to make it work in this way:

// source of copies, but notice the endslash, it's required 
// if you use the string replace method below
string selectedDrive = @"E:\temp\";  

string destFolderName = Path.Combine(selectedDrive, "Encrypted");
System.IO.Directory.CreateDirectory(destFolderName);

// All folders except the one just created
var allFolders = Directory.EnumerateDirectories(selectedDrive)
                          .Except(new[] { destFolderName });

// Loop over the sources
foreach (string source in allFolders)
{
    // this line in framework 4.8, 
    string relative = source.Replace(selectedDrive, "");

    // or this line if using NET Core 6
    // string relative = Path.GetRelativePath(selectedDrive, source));

    // Create the full destination name
    string dest = Path.Combine(destFolderName, relative);


    if (!Directory.Exists(dest))
    {
        FileSystem.CopyDirectory(source, dest);
    }

}

Also noted now that you are using a root drive (F:) as source for the directories to copy. In this case you should consider that you have other folders not accessible or not copy-able. (For example the Recycle.bin folder). However you can easily add other exclusions to the array passed to the IEnumerable extension Except

....
.Except(new[] { destFolderName, "Recycle.bin" });
  • Related