I have a location like: C:\Backups
I have multiple locations such as:
C:\Users\Peter\Books
C:\ProgramData\Library
C:\Tests\Testing\Tester\
How can I copy everything in each of the locations to the backup location, so that If I drop everything in the backup location folder into C: it will overwrite all the files there with the backup? Basically how can I create the entire structure for backup.
So Far:
public void Init()
{
_locationsToBackup = new List<string>();
DataSet dataSet = _settings.Pull();// dataset is set here
DataTable settingsTable = dataSet.Tables[0];
int valueIndex = 0;
foreach (DataColumn coll in settingsTable.Columns)
{
if (coll.ColumnName == "Value")
{
break;
}
valueIndex++;
}
foreach (DataRow row in settingsTable.Rows)
{
int start = 0;
foreach (DataColumn col in settingsTable.Columns)
{
if (col.ColumnName == "SettingType")
{
string settingRowValue = row.ItemArray[start].ToString();
int settingType = Convert.ToInt32(settingRowValue);
if (settingType == 3)
{
String location = row.ItemArray[valueIndex].ToString();
AddNewLocationToBackup(location);
break;
}
}
start++;
}
}
}
public void StartBackup()
{
//make sure backup folder exists in correct location
// if not then create it.
if(!Directory.Exists(#"C:\ProgramData\Test\Backups"))
{
Directory.CreateDirectory(#"C:\ProgramData\Test\Backups");
}
foreach(string currentLocation in LocationsToBackup)
{
if (Directory.Exists(currentLocation))
{
// copy all files from currentLocation and put into backups
CopyFilesToDirWithSamePath(currentLocation, #"C:\ProgramData\Test\Backups" + #"\" + currentLocation);
}
}
}
}
public void CopyFilesToDirWithSamePath(string sourceDirInput, string targetDirInput)
{
string sourceDir = sourceDirInput;
string targetDir = targetDirInput;
foreach (var file in Directory.GetFiles(sourceDir))
{
File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)), true);
}
}
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
I hope this will help you
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// 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 use FileSelectionManager library, take a look to this example:
http://www.fileselectionmanager.com/#Copying%20and%20moving%20files
Hope it hepls.
Related
One Question about coding (Visual Studio C# Windows form Application) There have Two folder: (Source and Target) and I build 1 button "Copy". In (Source) folder have random folders such "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 to "Target" folder?
Here my code for now, after I click a button the folder wouldn't copy. I guess there have some problem with this codes and I still not found it until. Hope you guys can help me, thank you.
*namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string FROM_DIR = "C:/Users/Desktop/Source/";
string TO_DIR = "C:/Users/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;
MessageBox.Show("success");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
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);
}
}
}
}
*}
By clicking the button, automatically copy all "201904**" folder and 3 ".txt files in (Source) folder to (target folder).
You didn't say which 3 txt files you want to copy so the code below copies all txt files, please explain how you select the files and I'll edit the code.
const string Source = #"C:\Users\Desktop\Source\";
const string Target = #"C:\Users\Desktop\Target\";
const string StartsWith = "201904";
const string FileType = "txt";
public static void Copy()
{
if (!Directory.Exists(Source)) //Check if the source directory exists
throw new Exception("Source directory is missing!");
Directory.CreateDirectory(Target); //If the target directory doesn't exists it will create one
var Directories = Directory.GetDirectories(Source, $"{StartsWith}*"); //Get directories which match the search pattern
for (int i = 0; i < Directories.Length; i++)
{
DirectoryInfo directory = new DirectoryInfo(Directories[i]);
Directory.CreateDirectory($"{Target}{directory.Name}"); //Create the directory in the target folder
var Files = Directory.GetFiles($"{Source}{directory.Name}", $"*.{FileType}"); //Get files
for (int j = 0; j < Files.Length; j++)
{
FileInfo file = new FileInfo(Files[j]);
File.Copy($"{Source}{directory.Name}" + #"\" + file.Name, $"{Target}{directory.Name}" + #"\" + file.Name); //Copy the file to the target folder
}
}
}
This code selects all directories which start with "201904" and all txt files inside them and copies it to the target folder.
EDIT: Fixed a mistake in the code
I am trying to make a program to backup files from a particular folder, along with the files within the subfolders of the main folder to another backup folder.
This is part of the code I am trying to accomplish the goal, however I am getting backed up only the files from the main folder, and the subfolders are being copied entirely(all of the files in them).
public static string[] Backup(string sourceDirectory, string targetDirectory, string backupDirectory)
{
DirectoryInfo diBackup = new DirectoryInfo(backupDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
List<string> dups = new List<string>();
string[] fileNamesSource = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories);
string[] fileNamesDest = Directory.GetFiles(targetDirectory, "*", SearchOption.AllDirectories);
List<string> dupNS = new List<string>();
List<string> dupND = new List<string>();
List<string> BCKP = new List<string>();
string replacement = "";
for (int i = 0; i < fileNamesDest.Length; i++)
{
string res = fileNamesDest[i].Replace(targetDirectory, replacement);
dupND.Add(res);
}
foreach (var ns in fileNamesSource)
{
string res = ns.Replace(sourceDirectory, replacement);
dupNS.Add(res);
}
var duplicates = dupND.Intersect(dupNS);
string[] DuplicatesStringArray = duplicates.ToArray();
foreach (var dup in DuplicatesStringArray)
{
string res = targetDirectory + dup;
BCKP.Add(res);
}
string[] ToBeBackedUp = BCKP.ToArray();
Directory.CreateDirectory(diBackup.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in diTarget.GetFiles())
{
if (ToBeBackedUp.Contains(fi.FullName)){
fi.CopyTo(Path.Combine(diBackup.FullName, fi.Name), true);
}
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in diTarget.GetDirectories())
{
if (ToBeBackedUp.Contains(diSourceSubDir.FullName)) {
DirectoryInfo nextTargetSubDir =
diBackup.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
return ToBeBackedUp;
}
Any ideas of how can I copy only the files in the subfolders that exist in the "source" folder?
Also the CopyAll function:
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
Thanks in advance.
You can try this way as
Much easier
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
A simple solution: in your CopyAll method, load the SearchOption.AllDirectories argument to your GetFiles method:
foreach (FileInfo fi in source.GetFiles("*", SearchOption.AllDirectories))
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
You can use Directory.GetFiles along with SearchOption.AllDirectories to extract the files from the sub-folders as well:
Directory.GetFiles(path, *search pattern goes here*, SearchOption.AllDirectories)
This question already has answers here:
Copy the entire contents of a directory in C#
(28 answers)
Copy file from one directory to another
(5 answers)
Closed 5 years ago.
Okay, so I have a text box in my program where a user can enter a value, however I am wanting to call this value in another class.
public static void Main()
{
string sourceDirectory = #"F:\RootFolder\testingfolder\Test";
string targetDirectory = #"c:\targetDirectory"; //this is where the value would site
Copy(sourceDirectory, targetDirectory);
}
Not 100% sure on how to call this.
Edit
After some much needed research I have found the below to work for me;
private void CopyInstallFiles(object sender, EventArgs e)
{
string sourceDirectory = #"F:somepath";
string targetDirectory = directoryImput.Text;
//Copy all the files & Replaces any files with the same name
foreach (string newPath in System.IO.Directory.GetFiles(sourceDirectory, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceDirectory, targetDirectory), true);
I just realized that you are looking for a method to move all files and folders - silly me. Here, have some example from https://msdn.microsoft.com/en-us/library/bb762914.aspx :
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);
}
}
}
}
Short version - place it in DirectoryManager.cs and call by DirectoryManager.CopyDirectory(source, destination):
using System.IO;
class DirectoryManager
{
internal static void CopyDirectory(string input, string output)
{
DirectoryInfo dir = new DirectoryInfo(input);
if (dir.Exists)
{
DirectoryInfo[] dirs = dir.GetDirectories();
Directory.CreateDirectory(output);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(output, file.Name);
file.CopyTo(temppath, false);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(output, subdir.Name);
CopyDirectory(subdir.FullName, temppath);
}
}
}
}
I am trying to remove all files on my storage card without removing one. I can keep the directory I specify but not its contents with my current code. It just leaves the blank
folder data because it removes everything inside. How can I keep it from removing that folder and its contents?
private void button1_Click(object sender, EventArgs e)
{
ScanDirectory scanDirectory = new ScanDirectory();
scanDirectory.WalkDirectory(#"/Storage Card");
scanDirectory.WalkDirectory(#"/Application");
}
public class ScanDirectory
{
public void WalkDirectory(string directory)
{
WalkDirectory(new DirectoryInfo(directory));
}
private static void WalkDirectory(DirectoryInfo directory)
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
The problem is the way in which the recursive function calls are done: the main function private static void WalkDirectory(DirectoryInfo directory) deletes all files and is called every time (even while analysing a subdirectory). Here you have a fix to make this code work as you wish:
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
private static void WalkDirectory(DirectoryInfo directory)
{
if (directory.Name.ToLower() != "data")
{
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
file.Attributes &= ~FileAttributes.ReadOnly;
var name = file.Name;
name = name.ToLower();
if (name != "test.txt")
{
file.Delete();
}
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
foreach (DirectoryInfo subDirectory in subDirectories)
{
WalkDirectory(subDirectory);
subDirectory.Attributes &= ~FileAttributes.ReadOnly;
var name = subDirectory.Name;
name = name.ToLower();
if (name != "data")
{
subDirectory.Delete();
}
}
}
}
I found a small snippet for doing a recursive file copy in C#, but am somewhat stumped. I basically need to copy a directory structure to another location, along the lines of this...
Source: C:\data\servers\mc
Target: E:\mc
The code for my copy function as of right now is...
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
}
// Copy each file into it’s new directory.
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(#"Copying {0}\{1}", targetDir, Path.GetFileName(file));
if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
{
int err = Marshal.GetLastWin32Error();
Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
}
}
The issue is that in the second scope, I either:
use Path.GetFileName(file) to get the actual file name without the path but I lose the directory "mc" directory structure or
use "file" without Path.Combine.
Either way I have to do some nasty string work. Is there a good way to do this in C# (my lack of knowledge with the .NET API leads me to over complicating things)
MSDN has a complete sample: How to: copy directories
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);
}
}
}
}
A non-recursive replacement for this answer would be:
private static void DirectoryCopy(string sourceBasePath, string destinationBasePath, bool recursive = true)
{
if (!Directory.Exists(sourceBasePath))
throw new DirectoryNotFoundException($"Directory '{sourceBasePath}' not found");
var directoriesToProcess = new Queue<(string sourcePath, string destinationPath)>();
directoriesToProcess.Enqueue((sourcePath: sourceBasePath, destinationPath: destinationBasePath));
while (directoriesToProcess.Any())
{
(string sourcePath, string destinationPath) = directoriesToProcess.Dequeue();
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
var sourceDirectoryInfo = new DirectoryInfo(sourcePath);
foreach (FileInfo sourceFileInfo in sourceDirectoryInfo.EnumerateFiles())
sourceFileInfo.CopyTo(Path.Combine(destinationPath, sourceFileInfo.Name), true);
if (!recursive)
continue;
foreach (DirectoryInfo sourceSubDirectoryInfo in sourceDirectoryInfo.EnumerateDirectories())
directoriesToProcess.Enqueue((
sourcePath: sourceSubDirectoryInfo.FullName,
destinationPath: Path.Combine(destinationPath, sourceSubDirectoryInfo.Name)));
}
}
instead of
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
do something like this
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}