Copy Folders in C# using System.IO - c#

I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
System.IO.Directory.Move(#"C:\FromFolder ", #"C:\ToFolder");
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne

This link provides a nice example.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
Here is a snippet
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}

there is a file copy.
Recreate folder and copy all the files from original directory to the new one
example
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}

Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).

yes you are right.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
has provided copy function ..
or you can use another function
http://msdn.microsoft.com/en-us/library/ms127960.aspx

You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.
string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
fileName=Path.GetFileName(s);
destFile = Path.Combine(DestinationPath, fileName);
File.Copy(s, destFile);
}
I leave creating the destination directory to you :-)

You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.
I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.

A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist
class Utils
{
internal static void copy_dir(string source, string dest)
{
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
Directory.CreateDirectory(dest);
foreach (string fn in Directory.GetFiles(source))
{
File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
}
foreach (string dir_fn in Directory.GetDirectories(source))
{
copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
}
}
}

This article provides an alogirthm to copy recursively some folder and all its content
From the article :
Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.
Good luck!

My version of DirectoryInfo.CopyTo using extension.
public static class DirectoryInfoEx {
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (!target.Exists)
target.Create();
foreach (FileInfo f in source.GetFiles()) {
FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
f.CopyTo(newFile.FullName, true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
diSourceSubDir.CopyTo(nextTargetSubDir);
}
}
}
And use like that...
DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));

Related

How to copy and paste a whole directory to a new path recursively?

I want to move a directory as a copy/paste routine, by keeping its structure as it is. I am not looking only for the files within all subfolders in a directory then copy/paste them (as this solution), instead I want to clone the whole thing and keep its structure as it is (Tree -> subfolders and files), exactly like a copy and paste routine.
So I found this function that copies a folder full of files to a new path:
Folder -> File(s)
The function behaves as known as the copy/paste routine. It takes SourcePath, DestinationPath and boolean value to OverWriteExisting. Nice and small but too bad it wasn't marked as the actual answer of that question there (recommend a rate).
But what if I want to move a whole directory? In other words, what if I have a folder that has folders of folders of folders of files and etc? And maybe it is unknown the file structure tree size like this:
Folder -> Folder(s) -> ... -> Folder(s) -> File(s)
I am using the below routine to copy/paste a folder that has folders. But here I know that I only have one level of folders so only one foreach loop is required:
foreach (var Folder in DestinationFolder) // here I know that I have only one level of folders to reach the files
{
CopyDirectory(FolderPath, DestinationPath, false); // use that function to copy the files
}
This above function serves this directory structure:
Folder -> Folder(s) -> File(s)
I tried this and it didn't do what I want. I only retrieve all files while it searches all the subfolders. Which is not what I want. I want to keep the subfolders and the original structure as it is. Here I get four files instead of the directory structed as it is, subfolders and their subfolders, subfolders, files. Only four because it removes duplicates which I do not want this to happen because I need all of them.
Here is my current structure(but my question is global to any directory):
Folder -> Folders -> Folders + Files
Here is what the below code does in the new path:
NewFolder -> AllFilesFoundInAnySubfolder
dialog.FileName = dialog.FileName.Replace(".xml", ""); // get the destination path
DirectoryInfo dirInfo = new DirectoryInfo(dialog.FileName);
if (dirInfo.Exists == false)
Directory.CreateDirectory(dialog.FileName);
List<String> EverythingInTheDirectory = Directory
.GetFiles(FileStructure.baseSessionPath + "\\" + SelectedSession.Name, "*.*", SearchOption.AllDirectories).ToList(); // source
foreach (string file in EverythingInTheDirectory)
{
FileInfo mFile = new FileInfo(file);
// to remove name collusion
if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
mFile.MoveTo(dirInfo + "\\" + mFile.Name);
}
How to move the whole directory with unknown size and keep its structure as it is? Not get only the files from a directory and move them!
Here is an example that will recursively clone a directory to another destination directory.
class Program
{
static void Main(string[] args)
{
CloneDirectory(#"C:\SomeRoot", #"C:\SomeOtherRoot");
}
private static void CloneDirectory(string root, string dest)
{
foreach (var directory in Directory.GetDirectories(root))
{
//Get the path of the new directory
var newDirectory = Path.Combine(dest, Path.GetFileName(directory));
//Create the directory if it doesn't already exist
Directory.CreateDirectory(newDirectory);
//Recursively clone the directory
CloneDirectory(directory, newDirectory);
}
foreach (var file in Directory.GetFiles(root))
{
File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));
}
}
}
A slight variation on code by #hawkstrider .
private static void CloneDirectory(DirectoryInfo source, DirectoryInfo dest) {
foreach (var source_subdir in source.EnumerateDirectories()) {
var target_subdir = new DirectoryInfo(Path.Combine(dest.FullName, source_subdir.Name));
target_subdir.Create();
CloneDirectory(source_subdir, target_subdir);
}
foreach (var source_file in source.EnumerateFiles()) {
var target_file = new FileInfo(Path.Combine(dest.FullName, source_file.Name));
source_file.CopyTo(target_file.FullName, true);
}
}
EDIT:
As #EtiennedeMartel correctly states, the Create() doesn't need the Exists check. ms-docs
Also Enumerations FTW!

How to copy sub-folder from folder into another folder?

I am working on C#.net console application in app i have two folders 1)D:\Working Projects\Alticore\AssetXML\LIS, 2)D:\Working Projects\Alticore\AssetXMLProcessed.
Now i want to copy only sub-folder(i.e LIS) from D:\Working Projects\Alticore\AssetXML\LIS to D:\Working Projects\Alticore\AssetXMLProcessed.
That is xaclty like this "D:\Working Projects\Alticore\AssetXMLProcessed/LIS".
Any solution to this problem I'll be appreciate.
Under Windows XP, it would be thus:
move "c:\documents and settings\%USERNAME%\desktop\TZClock" "C:\documents and settings\%USERNAME%\Start Menu\Programs\TZClock"
On Windows 7, it is the following (though I'm not in a position to test this right now):
move "c:\users\%USERNAME%\desktop\TZClock" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\TZClock"
you can execute this process or another thing create new file copy all data.
There is one more option what you can do is
there is
File.Copy(src, dest) method in the System.IO namespace you can also go with that.
This should do the job
public static void Copy(String srcPath, String destPath)
{
DirectoryInfo srcDirectory = new DirectoryInfo(srcPath);
if (!srcDirectory.Exists) return;
// Creates LIS directory
destPath = Path.Combine(Path.Combine(destPath, srcDirectory.Name));
Directory.CreateDirectory(destPath);
// Creates all sub directories from srcPath to your destPath
foreach (String dirPath in Directory.GetDirectories(srcPath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(srcPath, destPath));
// Copies all files from all sub directories from srcPath to your destPath
foreach (String copyPath in Directory.GetFiles(srcPath, "*.*", SearchOption.AllDirectories))
File.Copy(copyPath, copyPath.Replace(srcPath, destPath), true);
}
Usage:
Copy(#"D:\Working Projects\Alticore\AssetXML\LIS", #"D:\Working Projects\Alticore\AssetXMLProcessed")
If you don't want to copy sub folders or its files remove not needed foreach.
By the way it will override copied files.

copy files from one location to another

I am trying to create a directory and subdirectories and copy files from on one location to another location. The following code works but it doesn't create a parent directory(10_new) if there are sub directories. I am trying to copy all the contents(including subdirectories) from "c:\\sourceLoc\\10" to "c:\\destLoc\\10_new" folder. If "10_new" doesn't exist then I should create this folder. Please assist.
string sourceLoc = "c:\\sourceLoc\\10";
string destLoc = "c:\\destLoc\\10_new";
foreach (string dirPath in Directory.GetDirectories(sourceLoc, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourceLoc, destLoc));
if (Directory.Exists(sourceLoc))
{
//Copy all the files
foreach (string newPath in Directory.GetFiles(sourceLoc, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceLoc, destLoc));
}
}
From looking at your code, you never check for the existence of the parent folders. You jump to getting all the child folders first.
if (!Directory.Exists(#"C:\my\dir")) Directory.CreateDirectory(#"C:\my\dir");
Here is how to copy all files in a directory to another directory
This is taken from http://msdn.microsoft.com/en-us/library/cc148994.aspx
string sourcePath = "c:\\sourceLoc\\10";
string targetPath = "c:\\destLoc\\10_new";
string fileName = string.Empty;
string destFile = string.Empty;
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
Recursive Directory/Sub-directory
public class RecursiveFileSearch
{
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
static void Main()
{
// Start with drives if you have to search the entire computer.
string[] drives = System.Environment.GetLogicalDrives();
foreach (string dr in drives)
{
System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
// Here we skip the drive if it is not ready to be read. This
// is not necessarily the appropriate action in all scenarios.
if (!di.IsReady)
{
Console.WriteLine("The drive {0} could not be read", di.Name);
continue;
}
System.IO.DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);
}
// Write out all the files that could not be processed.
Console.WriteLine("Files with restricted access:");
foreach (string s in log)
{
Console.WriteLine(s);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key");
Console.ReadKey();
}
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
// First, process all the files directly under this folder
try
{
files = root.GetFiles("*.*");
}
// This is thrown if even one of the files requires permissions greater
// than the application provides.
catch (UnauthorizedAccessException e)
{
// This code just writes out the message and continues to recurse.
// You may decide to do something different here. For example, you
// can try to elevate your privileges and access the file again.
log.Add(e.Message);
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
// In this example, we only access the existing FileInfo object. If we
// want to open, delete or modify the file, then
// a try-catch block is required here to handle the case
// where the file has been deleted since the call to TraverseTree().
Console.WriteLine(fi.FullName);
}
// Now find all the subdirectories under this directory.
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
WalkDirectoryTree(dirInfo);
}
}
}
}
Before doing File.Copy, check to make sure the folder exists. If it doesn't create it.
This function will check if a path exists, if it doesnt, it will create it. If it fails to create it, for what ever reason, it will return false. Otherwise, true.
Private Function checkDir(ByVal path As String) As Boolean
Dim dir As New DirectoryInfo(path)
Dim exist As Boolean = True
If Not dir.Exists Then
Try
dir.Create()
Catch ex As Exception
exist = False
End Try
End If
Return exist
End Function
Remember, all .Net languages compile down to the CLR (common language runtime) so it does not matter if this is in VB.Net or C#. A good way to convert between the two is: http://converter.telerik.com/
It is impossible to copy or move files with C# in windows 7.
It will instead create a file of zero bytes.

C# merge one directory with another

I have an autoupdater C# program. It will download a rar file that holds the changed or new files for the update to some software. The rar file has it's structure just like the base directory of the software but only contains changed or new files/folders. Is there an easy way to "merge" these files/folders to the destination directory so in that if the file/folder exists already it'll be replaced and if not it'll be added or do I have to manually walk through each file/folder and do this myself? Just hoping there is a nice little merge function that .NET has :)
DirectoryInfo Class
The following example demonstrates how to copy a directory and its contents.
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
if (source.FullName.ToLower() == target.FullName.ToLower())
{
return;
}
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it's new directory.
foreach (FileInfo fi in source.GetFiles())
{
Console.WriteLine(#"Copying {0}\{1}", target.FullName, fi.Name);
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
The simplest way is to use the FileSystem.MoveDirectory method. Make sure you add a reference to the Microsoft.VisualBasic.dll:
using Microsoft.VisualBasic.FileIO;
...
// Merge D:\SourceDir with D:\DestDir:
FileSystem.MoveDirectory("D:\\SourceDir", "D:\\DestDir", true /* Overwrite */);

VSS in C# NET DirectoryCopy Function

I am writing a class (based on a class library) that creates a RAMDisk, and every X minutes I need to backup the contents of the RAMDisk to a physical location due to volatility. It was suggested to use CopyFileEx, as apparently the .NET file copy methods do not work.
For some reason I am getting an Invalid Arguements error when trying to use CopyFileEx though. I am assuming that I can still use the rest of the .NET methods in this function, but could just use some help fixing/cleaning it up a bit.
public static void CopyDirectoryVSS(string sourcePath, string targetPath)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(targetPath) == false)
{
Directory.CreateDirectory(targetPath);
}
// Copy each file into it’s new directory.
foreach (string dir in Directory.GetDirectories(sourcePath))
{
foreach (string file in Directory.GetFiles(dir, "*.*"))
{
Console.WriteLine(#"Copying {0}\{1}", targetPath, file);
CopyFileEx(file, Path.Combine(target, file), null, 0, 0, 0);
}
}
// Copy each subdirectory using recursion.
DirectoryInfo sourceDir = new DirectoryInfo(#sourcePath);
DirectoryInfo TargetDir = new DirectoryInfo(targetPath);
foreach (DirectoryInfo diSourceSubDir in sourceDir.GetDirectories())
{
DirectoryInfo nextTargetSubDir = TargetDir.CreateSubdirectory(diSourceSubDir.Name);
CopyDirectory(diSourceSubDir, nextTargetSubDir);
}
}
Check out the answer here: I'm guessing that copy solution would be cleaner and you're essentially doing the same thing:
Copying Files Recursively

Categories

Resources