Move all files and Subdirectories from a folder to another Subdirectory of the same folder

11,261

Solution 1

This is gonna be very simple.

Directory.Move("SourcePath", "DestinationPath");

Process all directories in the source folder and use the above syntax for each and every folder using forloop or foreach to move to your destination folder.

Solution 2

        string source = @"d:\test";
        string dest = @"d:\move\";

        DirectoryInfo dirInfo = new DirectoryInfo(dest);
        if (dirInfo.Exists == false)
            Directory.CreateDirectory(dest);


        DirectoryInfo dir = new DirectoryInfo(source);
        DirectoryInfo[] dirs = dir.GetDirectories();


        string[] files = Directory.GetFiles(source);
        Int32 i = dirs.Count() + files.Count();
        //   for progress bar

        foreach (string file in files)
        {
            try
            {
                string name = Path.GetFileName(file);
                string destFile = Path.Combine(dest, name);
                // skip some file
                if (name != "file") File.Move(file, destFile);
            }
            catch
            {

            }
        }

        foreach (DirectoryInfo subdir in dirs)
        {
            string temppath = Path.Combine(dest, subdir.Name);
            if (!Directory.Exists(temppath))
                try
                {
                    Directory.Move(subdir.FullName, temppath);
                }
                catch
                {

                }
        }
Share:
11,261

Related videos on Youtube

Indigo
Author by

Indigo

Updated on September 22, 2022

Comments

  • Indigo
    Indigo less than a minute

    I want to move all files and subdirectories including files to another subdirectory of the same folder.

    e.g. I have folder named abcd inside I have a file aa and subfolders bb, cc, dd. SO I would like to create another subdirectory inside the same folder as abcd\backup and move aa, bb, cc, dd i.e. all files and folder to backup folder.

  • Sagotharan
    Sagotharan over 8 years
    SA not asking for moving files, he want a backup so Copy is a good thing.
  • anindis
    anindis almost 7 years
    This won't work for a network path: \\server\folder\. It will throw an exception, that it can not find a path part
  • tony09uk
    tony09uk over 6 years
    @anindis wouldn't Server.MapPath() resolve that issue?
  • Ryan Leach
    Ryan Leach about 4 years
    This doesn't answer the question, this will move and remove the Source directory, question asks for all files and folders in directory to move to a sub folder (maintaining structure).