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);
}
Related
I want to copy all files from the current folder to another folder inside that.
but excluding few files which is a .exe file and a .dll file.
this is the code i have right now, this copies every file from current to the other folder. i have searched and got few answers to exclude based on the extensions but that isnt what i was looking for. i want to exclude based on their name so that i can exclude more files later on.
string TargetDirectory = #"Copied";
if (Directory.Exists(TargetDirectory))
{
Directory.Delete(TargetDirectory, true);
}
Directory.CreateDirectory(TargetDirectory);
await Task.Delay(1000);
string SourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Logger.LogInfo("Creating Backup of the Source Directory...");
if (Directory.GetFiles(SourceDirectory).Length == 0)
{
Logger.LogError("No Files found in this directory. " + SourceDirectory);
return;
}
else
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourceDirectory, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourceDirectory, TargetDirectory));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourceDirectory, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourceDirectory, TargetDirectory), true);
}
This should work:
HashSet<string> namesToExclude = new HashSet<string>()
{
"bla.dll",
"blubb.exe"
};
string TargetDirectory = #"Copied";
if (Directory.Exists(TargetDirectory))
{
Directory.Delete(TargetDirectory, true);
}
Directory.CreateDirectory(TargetDirectory);
await Task.Delay(1000);
string SourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Logger.LogInfo("Creating Backup of the Source Directory...");
if (Directory.GetFiles(SourceDirectory).Length == 0)
{
Logger.LogError("No Files found in this directory. " + SourceDirectory);
return;
}
else
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourceDirectory, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourceDirectory, TargetDirectory));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourceDirectory, "*.*", SearchOption.AllDirectories))
{
if (!namesToExclude.Contains(Path.GetFileName(newPath)))
{
File.Copy(newPath, newPath.Replace(SourceDirectory, TargetDirectory), true);
}
}
}
Oh and as a sidenote, your code will not copy if there are only directories and no files inside the root directory, you might want to check for directories as well. And subdirectories will be a problem as well. You could use recursion to fix this.
Try, that should work:
async Task<void> Copy(List<string> ExcludedNamesWithoutExtensions)
{
string TargetDirectory = #"Copied";
if (Directory.Exists(TargetDirectory))
{
Directory.Delete(TargetDirectory, true);
}
Directory.CreateDirectory(TargetDirectory);
await Task.Delay(1000);
string SourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Logger.LogInfo("Creating Backup of the Source Directory...");
if (Directory.GetFiles(SourceDirectory).Length == 0)
{
Logger.LogError("No Files found in this directory. " + SourceDirectory);
return;
}
else
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourceDirectory, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(dirPath.Replace(SourceDirectory, TargetDirectory));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourceDirectory, "*.*", SearchOption.AllDirectories))
{
bool CanCopy = true;
string[] array = newPath.Split('\\')[newPath.Split('\\').Length - 1].Split('.');
string name = array[array.Length - 1];
foreach (string s in ExcludedNamesWithoutExtensions)
{
if (name != s)
{
CanCopy = false;
break;
}
}
if (CanCopy)
File.Copy(newPath, newPath.Replace(SourceDirectory, TargetDirectory), true);
}
}
}
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);
}
}
}
}
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();
......
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);
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