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);
}
}
}
}
Related
Good day.
I have to copy all the files in folders (including sub folders) to other shared drive location for backup the data. The challenge, which I am facing is folder path with wildcard characters.
For example,
The folder structure is like below
D:/Folder1/Folder11/Folder111
D:/Folder2/Folder222/Folder222222
D:/Folder3/Folder333333/Folder3333333
I am looking for the input format should be "D:/Folder?/Folder*/Folder*". So that it has to loop according to the wildcard character patterns.
Can you please help me.
Regards,
Chandra
You can achive this with a simple RegularExpression. I've created an example which does the job for you.
The RegEx string is quite easy: [A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
----- -------- -------- --------
Drive 1x digit 2x digit 3x digit
See the sample at regexr.
EDIT:
//using System.IO;
public void CopyMatching(string drive)
{
try
{
var backuplocation = ""; //the path where you wanna copy your files to
var regex = new Regex(#"[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}");
var directories = new List<string>();
foreach (var directory in Directory.EnumerateDirectories(drive))
{
if (regex.IsMatch(directory))
{
directories.Add(directory);
}
}
foreach (var directory in directories)
{
DirectoryCopy(directory, backuplocation, true);
}
}
catch (Exception)
{
throw;
}
}
And DirectoryCopy:
public 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);
}
}
}
IEnumerable<string> getMatchingSubDir(string dirPath, string pattern)
{
List<string> matchingFolders = new List<string>();
DirectoryInfo myDir = new DirectoryInfo(dirPath);
foreach (var subDir in myDir.GetDirectories(pattern))
{
matchingFolders.AddRange(getMatchingSubDir(subDir.FullName, pattern));
}
return matchingFolders;
}
Then this call will return you a list of all folders matching your pattern:
getMatchingSubDir("D:\\", "Folder*");
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
using System.IO;
namespace ConsoleApplication3
{
public class SimpleFileCopy
{
static void Main()
{
string sourcePath = #"C:\Source\";
string targetPath = #"C:\Files\";
if (Directory.Exists(sourcePath))
{
DirectoryInfo dirinfo = new DirectoryInfo(sourcePath);
DirectoryInfo[] listofSubDir=dirinfo.GetDirectories();
foreach (var item in listofSubDir)
{
var childItem = item.FullName + "\\" + "C1";
string[] files = System.IO.Directory.GetFiles(childItem);
foreach (var file in files)
{
Console.WriteLine(file);
}
}
Console.Read();
}
}
}
}
Copying from MSDN, there is the following solution. It recursively copies directories over from source to destination.
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);
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 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.
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);
}
This question already has answers here:
Copy the entire contents of a directory in C#
(28 answers)
Closed 6 years ago.
I have a folder with 10 text files at C:\TEXTFILES\ drive in my machine. I want to copy the folder TEXTFILES and its contents completely from my machine to another machine. How to copy the same using C#.
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
DirectoryCopy(".", #".\temp", true);
}
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))
{
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);
}
}
}
}
From MSDN
private void copyDirectory(string strSource, string strDestination)
{
if (!Directory.Exists(strDestination))
{
Directory.CreateDirectory(strDestination);
}
DirectoryInfo dirInfo = new DirectoryInfo(strSource);
FileInfo[] files = dirInfo.GetFiles();
foreach(FileInfo tempfile in files )
{
tempfile.CopyTo(Path.Combine(strDestination,tempfile.Name));
}
DirectoryInfo[] directories = dirInfo.GetDirectories();
foreach(DirectoryInfo tempdir in directories)
{
copyDirectory(Path.Combine(strSource, tempdir.Name), Path.Combine(strDestination, tempdir.Name));
}
}
string path = #"C:\TEXTFILES\";
string path2 = #"P:\myNetworkPath\tesssst";
try
{
Directory.CreateDirectory(path2);
foreach (string fileName in Directory.GetFiles(path))
{
File.Copy(
Path.Combine(path, fileName),
Path.Combine(path2, fileName), true);
}
}
catch
{
Console.WriteLine("Exception");
}
For a deeper copy, see:
http://www.codeproject.com/KB/files/copydirectoriesrecursive.aspx
Share your destination folder.
There are a lot of ways to do this. See followings:
Copy Folders in C# using System.IO
Copy the entire contents of a directory in C#