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
{
}
}
Related videos on Youtube
Author by
Indigo
Updated on September 22, 2022Comments
-
Indigo about 1 year
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 over 9 yearsSA not asking for moving files, he want a backup so Copy is a good thing.
-
anindis about 8 yearsThis won't work for a network path: \\server\folder\. It will throw an exception, that it can not find a path part
-
tony09uk almost 8 years@anindis wouldn't Server.MapPath() resolve that issue?
-
Ryan Leach over 5 yearsThis 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).