Move Images from ladder Sub folders to Main Folder using C# - c#

In my project I have to move the files in Main Folder Which locate in Sub-folders. the Below code move the First and second sub-folder files only. How can I move all the sub folders file to main folder.
Calling function -
MoveFilesToMain(#"F:\Test\New folder", #"F:\Test");
Function -
public static void MoveFilesToMain(string sourceDirName, string destDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
File.Move(Path.Combine(sourceDirName, file.Name), Path.Combine(destDirName, file.Name));
}
foreach (DirectoryInfo subdir in dirs)
{
FileInfo[] files1 = subdir.GetFiles();
foreach (FileInfo file in files1)
{
File.Move(Path.Combine(subdir.FullName, file.Name), Path.Combine(destDirName, file.Name));
}
}
}
Below marked folders files are not moved.

a little bit of recursion should do the trick.
basically for a given source dir, we copy the files into the dest dir. then iterate through every sub dir in the source dir and repeat the process recursively.
public static void MoveFilesToMain(string sourceDirName, string destDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
if (files.Length == 0 && dirs.Length == 0)
{
Directory.Delete(sourceDirName, false);
return;
}
foreach (FileInfo file in files)
{
File.Move(Path.Combine(sourceDirName, file.Name), Path.Combine(destDirName, file.Name));
}
foreach (DirectoryInfo subdir in dirs)
{
MoveFilesToMain(subdir.FullName, destDirName)
}
}

Try this:
DirectoryInfo[] dirs = dir.GetDirectories("*",SearchOption.AllDirectories);

Related

Copy specific Folder with 3 Files only to New Folder

One Question about coding (Visual Studio C# WindowsformApplication) There have Two folder: (Source and Target) and I build 1 button "Copy".
In "Source" folder have random folders such as "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Every these folders have [10] .txt files. What is the coding if I only want to copy all "201904**" folders with [3] .txt files inside it to "Target" folder? Here is my code for now.
Code
** private void button1_Click
{
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string directname = "201904";
string filename = ".txt";
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name == "2019")
{
foreach (DirectoryInfo direc in newfile.GetDirectories())
if (direc.Name.StartsWith(directname))
{
int count = 0;
foreach (FileInfo file in direc.GetFiles())
{
if (file.Name.EndsWith(filename))
{
count++;
}
}
if (count == 3)
{
DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
count = 0;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("success");
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}**
I expect after I click a button,
output is automatically copy all folders Name Start With "201904**" with [3] text files inside from "Source" folder to "target" folder.
I reckon you can search the directory with names directly using linq and can copy the sub folders/files inside it like below. It will give you the flexibility of filtering folders/files/skipping/taking n folders/files
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
string searchText = "201904";
string extension = "txt";
IEnumerable<string> dirs = Directory.EnumerateDirectories(FROM_DIR, "*", SearchOption.AllDirectories)
.Where(dirPath=>Path.GetFileName(dirPath.TrimEnd(Path.DirectorySeparatorChar)).StartsWith(searchText));
foreach (string dir in dirs)
{
string destDirPath = dir.Replace(FROM_DIR, TO_DIR);
if (!Directory.Exists(destDirPath))
Directory.CreateDirectory(destDirPath);
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.EnumerateFiles(dir, string.format("*.{0}",extension),
SearchOption.AllDirectories))// Here you can skip/take n files if u need
File.Copy(newPath, newPath.Replace(FROM_DIR, TO_DIR), true);
}
Have tested with sub folders and files inside source folder as well. Hope it helps.

Copy all content from the folder into two file destination folder

I want to copy all the content in a folder into two file destination folder.
foreach (string newPath in Directory.GetFiles(#"E:\autotransfer", "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(#"E:\autotransfer",
#"E:\autotransferbackup"), true);
foreach (string newPath in Directory.GetFiles(#"E:\autotransfer", "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(#"E:\autotransfer",
#"E:\autotransferbackupcp"), true);
You can use this code, for more information see the answer here: Copy all files in directory
void Copy(string sourceDir, string targetDir)
{
Directory.CreateDirectory(targetDir);
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(sourceDir))
Copy(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
}
private void button1_Click(object sender, EventArgs e)
{
Copy("E:\autotransfer", "E:\autotransferbackup");
Copy("E:\autotransfer", "E:\autotransferbackupcp");
}
If the directory structure is not the same, then you will need to check if the folder exists, if not, create it first, then copy the files.
Taken from here on msdn: https://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx
You can copy this function and use it in your code.
Hope this helps.
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", #".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}

Creating a log of a backup C#

So I want to log what happens when I backup files but I'm not sure how to make it work for files in subdirectories aswell.
Right now I have this code that works for all files in the selected directory but doesn't work for subdirectory files
private void LogBackup(string sourceDirName, string destDirName)
{
List<string> lines = new List<string>();
string logDestination = this.tbox_LogFiles.Text;
string dateString = DateTime.Now.ToString("MM-dd-yyyy_H.mm.ss");
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
lines.Add("FILES TO COPY:");
lines.Add("--------------");
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files
.Where(f => !extensionsToSkip.Contains(f.Extension) && !filesToSkip.Contains(f.FullName)).ToList())
{
string desttemppath = Path.Combine(destDirName, file.Name);
string sourcetemppath = Path.Combine(sourceDirName, file.Name);
lines.Add("SOURCE FILE:");
lines.Add(sourcetemppath);
lines.Add("DESTINATION FILE:");
lines.Add(desttemppath);
lines.Add("");
}
foreach (DirectoryInfo subdir in dirs
.Where(f => !foldersToSkip.Contains(f.FullName)))
{
//NOT SURE WHAT TO WRITE HERE
}
using (StreamWriter writer = new StreamWriter(logDestination + #"\LOG " + dateString + ".txt"))
{
foreach (string line in lines)
{
writer.WriteLine(line);
}
}
}
Any ideas please?
Include the SearchOption.AllDirectories and you will get all sub directories:
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories("*", SearchOption.AllDirectories);
when you now loop through the directories, you will have also the first level of subdirectories and for each directory just get the files that it contains
foreach (DirectoryInfo subdir in dirs)
{
FileInfo[] files = subdir.GetFiles();
......

Sub folders are not copyied

I am using the function on this SO post to copy folders content into another folder, but it's not copying the sub folders and their content.
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Debug.Log("Directory created.." + destDirName);
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
This is how it's called:
string destingationPath = startupFolder + #"\NetworkingDemoPlayerWithNetworkAwareShooting1_Data";
DirectoryCopy("NetworkingDemoPlayerWithNetworkAwareShooting1_Data", destingationPath, true);
I agree that your code looks correct
Windows system error 112 means there is not enough space on the disk

How to copy files in subdirectory?

How to modify the code to copy and files in subdirectoryes of tempDownloadFolder?
private void moveFiles()
{
DirectoryInfo di = new DirectoryInfo(tempDownloadFolder);
FileInfo[] files = di.GetFiles();
foreach (FileInfo fi in files)
{
if (fi.Name != downloadFile)
File.Copy(tempDownloadFolder + fi.Name, destinationFolder + fi.Name, true);
}
}
You need to do a recursive search.
very rough example:
private void copyFiles(string filePath)
{
DirectoryInfo di = new DirectoryInfo(filePath);
FileInfo[] files = di.GetFiles();
foreach (FileInfo fi in files)
{
// test if fi is a directory
// if so call copyFiles(fi.FullName) again
// else execute the following
if (fi.Name != downloadFile) File.Copy(filePath+ fi.Name, destinationFolder + fi.Name, true);
}
}
If you want files of all subdirectories use the SearchOption parameter:
DirectoryInfo di = new DirectoryInfo(tempDownloadFolder);
di.GetFiles("*.*", SearchOption.AllDirectories);
FileInfo[] files = di.GetFiles();
foreach (FileInfo fi in files)
{
if (fi.Name != downloadFile)
File.Copy(tempDownloadFolder + fi.Name, destinationFolder + fi.Name, true);
}
Replace the File.Copy line by
File.Copy(fi.FullName, Path.Combine(destinationFolder, fi.Name), true);
Just find working solution here:
http://www.codeproject.com/Articles/3210/Function-to-copy-a-directory-to-another-place-noth?msg=4571843#xx4571843xx

Categories

Resources