How to copy files in subdirectory? - c#

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

Related

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();
......

How to copy selected folders, subfolders and files from openFileDialog in c#

I have a function that is suposed to copy all folders, subfolders files selected from openFileDialog from a location to another:
I've made this function to copy all the selected paths:
public void CopiarFicheiros(string CopyTo, List<string> FilesToCopy )
{
foreach (var item in FilesToCopy)
{
string DirectoryName = Path.GetDirectoryName(item);
string Copy = Path.Combine(CopyTo, DirectoryName);
if (Directory.Exists(Copy) && DirectoryName.ToLower() != "newclient" && DirectoryName.ToLower() != "newservice")
{
Directory.CreateDirectory(Copy);
File.Copy(item, Copy + #"\" + Path.GetFileName(item), true);
}
else File.Copy(item, CopyTo + #"\" + Path.GetFileName(item), true);
}
}
The logic is full of flaws and I'm running out of time and can't seem to find a proper solution to this.
This is how I get the selected files and folders from the dialog:
private List<string> GetFiles()
{
var Files = new List<string>();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string sFileName = openFileDialog.FileName;
string[] arrAllFiles = openFileDialog.FileNames;
Files = arrAllFiles.ToList();
}
return Files;
}
Does anyone have a better solution or a clue to what I need to change to successfully do this?
Any help is highly appreciated, thank you
Don't use OpenFileDialog to choose the folder. As the name suggests, it not made for that task. You want the FolderBrowserDialog class for this task.
How to: Copy Directories:
// 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);
}
}
}

Copy directory with all files and folders

I'm trying to copy one directory to another path.
I found this method, but it does not copy the directory, only the sub-directories and files inside it:
string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");
foreach (string dirPath in Directory.GetDirectories(sourcedirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcedirectory, folderDialog.SelectedPath));
}
foreach (string newPath in Directory.GetFiles(sourcedirectory, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcedirectory, folderDialog.SelectedPath), true);
}
How I can get the "Program" folder in output with all files and sub-folders?
If you adjust the output path before you start copying, it should work:
string sourcedirectory = Environment.ExpandEnvironmentVariables("%AppData%\\Program");
folderDialog.SelectedPath = Path.Combine(folderDialog.SelectedPath,
Path.GetFileName(sourcedirectory));
foreach (string dirPath in Directory.GetDirectories(sourcedirectory, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcedirectory, folderDialog.SelectedPath));
}
foreach (string newPath in Directory.GetFiles(sourcedirectory, "*.*", SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcedirectory, folderDialog.SelectedPath), true);
}
You can use a recursive function to do it:
private void button1_Click(object sender, EventArgs e)
{
this.CopyAll(new DirectoryInfo(#"D:\Original"), new DirectoryInfo(#"D:\Copy"));
}
private void CopyAll(DirectoryInfo oOriginal, DirectoryInfo oFinal)
{
foreach (DirectoryInfo oFolder in oOriginal.GetDirectories())
this.CopyAll(oFolder, oFinal.CreateSubdirectory(oFolder.Name));
foreach (FileInfo oFile in oOriginal.GetFiles())
oFile.CopyTo(oFinal.FullName + #"\" + oFile.Name, true);
}

Move Images from ladder Sub folders to Main Folder using 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);

Categories

Resources