I am working on an asp.net application where i have to move any Folder and its contents to another. Suppose i have a Main folder and in that folder there is 3 subfolders. In each subfolder there is a file. I want to move folder and all its contents to another place. For this i used the following code
if (!Directory.Exists(#"E:\Sunny\C#FolderCopy"))
{
Directory.CreateDirectory(#"E:\Sunny\C#FolderCopy");
Directory.Move(#"E:\Sunny\C#Folder\", #"E:\Sunny\C#FolderCopy\");
}
But when the control reaches to move function The error comes as
Cannot create a file when that file already exists.
How to solve this
Directory.Move already creates the folder for you. You only need to adjust to the following:
if (!Directory.Exists(#"E:\Sunny\C#FolderCopy"))
{
Directory.Move(#"E:\Sunny\C#Folder\", #"E:\Sunny\C#FolderCopy\");
}
If you want to copy the folder (as indicated by your comment) you can use FileSystem.CopyDirectory. It is located in a Visual Basic namespace but that should be of no concern at all:
using Microsoft.VisualBasic.FileIO;
if (!Directory.Exists(#"E:\Sunny\C#FolderCopy"))
{
FileSystem.CopyDirectory(#"E:\Sunny\C#Folder\", #"E:\Sunny\C#FolderCopy\");
}
Or use this method (taken from msdn):
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);
}
}
}
Recursive Files Move.
Call this method and all it do.
public static void MoveDirectory(string source, string target)
{
var sourcePath = source.TrimEnd('\\', ' ');
var targetPath = target.TrimEnd('\\', ' ');
var files = Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)
.GroupBy(s=> Path.GetDirectoryName(s));
foreach (var folder in files)
{
var targetFolder = folder.Key.Replace(sourcePath, targetPath);
Directory.CreateDirectory(targetFolder);
foreach (var file in folder)
{
var targetFile = Path.Combine(targetFolder, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile);
File.Move(file, targetFile);
}
}
Directory.Delete(source, true);
}
Related
One Question about coding (Visual Studio C# WindowsformApplication) There have Two folder: (Source and Target) and I build 1 button "Copy".
In "Source" folder have random folders such as "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 it to "Target" folder? Here is my code for now.
Code
** private void button1_Click
{
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/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;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("success");
}
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);
}
}
}**
I expect after I click a button,
output is automatically copy all folders Name Start With "201904**" with [3] text files inside from "Source" folder to "target" folder.
I reckon you can search the directory with names directly using linq and can copy the sub folders/files inside it like below. It will give you the flexibility of filtering folders/files/skipping/taking n folders/files
string FROM_DIR = "C:/Users/5004117928/Desktop/Source";
string TO_DIR = "C:/Users/5004117928/Desktop/Target/";
string searchText = "201904";
string extension = "txt";
IEnumerable<string> dirs = Directory.EnumerateDirectories(FROM_DIR, "*", SearchOption.AllDirectories)
.Where(dirPath=>Path.GetFileName(dirPath.TrimEnd(Path.DirectorySeparatorChar)).StartsWith(searchText));
foreach (string dir in dirs)
{
string destDirPath = dir.Replace(FROM_DIR, TO_DIR);
if (!Directory.Exists(destDirPath))
Directory.CreateDirectory(destDirPath);
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.EnumerateFiles(dir, string.format("*.{0}",extension),
SearchOption.AllDirectories))// Here you can skip/take n files if u need
File.Copy(newPath, newPath.Replace(FROM_DIR, TO_DIR), true);
}
Have tested with sub folders and files inside source folder as well. Hope it helps.
I am using the function on this SO post to copy folders content into another folder, but it's not copying the sub folders and their content.
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))
{
Debug.Log("Directory created.." + 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);
}
}
}
This is how it's called:
string destingationPath = startupFolder + #"\NetworkingDemoPlayerWithNetworkAwareShooting1_Data";
DirectoryCopy("NetworkingDemoPlayerWithNetworkAwareShooting1_Data", destingationPath, true);
I agree that your code looks correct
Windows system error 112 means there is not enough space on the disk
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);
}
}
}
Now here is the problem:
I have a lot of code that all does the same thing. That is, it copies the contents of two folders into a destination folder and merges them in the destination folder. My problem is, I cannot find out (after much Googling) how to actually copy the source directories + contents as opposed to just its contents and sub folders which then end up merged.
It may be how I'm obtaining the directories: I use a Folder Selection Dialog, add the path name to a listbox (To display) and then create a list of (string) directories from the items in the listbox.
Here is the code so far. (Some is from MSDN)
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())
{
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);
}
}
//This is inside a button click Method
List<string> pathList = new List<string>();
pathList = lstBox.Items.Cast<String>().ToList();
string sourceDirectory;
string targetDirectory;
DirectoryInfo dirSource;
DirectoryInfo dirTarget;
for (int i = 0 ; i < pathList.Count; i++)
{
sourceDirectory = pathList.ElementAt(i);
targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog
dirSource = new DirectoryInfo(sourceDirectory);
dirTarget = new DirectoryInfo(targetDirectory);
CopyAll(dirSource, dirTarget);
}
Annoyingly C# has no Directory.Copy function which would be extremely useful.
Recap.
I Select Folder 1.
I select Folder 2.
I Select Destination Folder.
I Press OK.
Expected Result: Destination Folder has two folders, Folder 1 and Folder 2 inside. Both has all files inside.
Actual Result: Destination Folder has loose files merged, and sub directories of source folders intact. (Which is whats annoying)
I hope this is enough info for you professionals to help with.
The problem is you are never making a new target for your destination -- this will make a new target with the same name as the source for each iteration of the loop and then copy to that target.
for (int i = 0 ; i < pathList.Count; i++)
{
sourceDirectory = pathList.ElementAt(i);
targetDirectory = browserSave.SelectedPath; //browserSave is the Folder Selection Dialog
dirSource = new DirectoryInfo(sourceDirectory);
string targetPath = target.Fullname+
Path.DirectorySeparatorChar+
sourceDirectory.Split(Path.DirectorySeparatorChar).Last());
Directory.CreateDirectory(targetPath);
dirTarget = new DirectoryInfo(targetPath);
CopyAll(dirSource, dirTarget);
}
caveat I did not test so I might have typos, but you get the idea.
Instead of DirectoryInfo pass string as a parameter. See the code below.
private 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);
}
}
}
In main function.
static void Main(string[] args)
{
List<string> directoryNames = new List<string>() // For multiple source folders
{
"C:\\Folder1", "C:\\Folder2"
};
string destDirName = "C:\\Folder3";
foreach (string sourceDirName in directoryNames)
{
DirectoryCopy(sourceDirName, destDirName, true)
}
}
Try the following. You'll obviously need to set the source and destination folders accordingly when you invoke action. Also I would suggest that you do not embed any logic in event handlers.
Hope this helps.
Action<string, string> action = null;
action = (source,dest) =>
{
if(Directory.Exists(source))
{
DirectoryInfo sInfo = new DirectoryInfo(source);
if (!Directory.Exists(dest))
{
Directory.CreateDirectory(dest);
}
Array.ForEach(sInfo.GetFiles("*"), a => File.Copy(a.FullName, Path.Combine(dest,a.Name)));
foreach (string dir in Directory.EnumerateDirectories(source))
{
string sSubDirPath = dir.Substring(source.Length+1,dir.Length-source.Length-1);
string dSubDirPath = Path.Combine(dest,sSubDirPath);
action(dir, dSubDirPath);
}
}
};
action(#"C:\source", #"C:\dest");
This will help you to solve your problem.This function is a generic recursive function for copy folder with or not sub folders with merging.
public static void DirectoryCopy(string sourceDirPath, string destDirName, bool isCopySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirPath);
DirectoryInfo[] directories = directoryInfo.GetDirectories();
if (!directoryInfo.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "
+ sourceDirPath);
}
DirectoryInfo parentDirectory = Directory.GetParent(directoryInfo.FullName);
destDirName = System.IO.Path.Combine(parentDirectory.FullName, destDirName);
// 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 = directoryInfo.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = System.IO.Path.Combine(destDirName, file.Name);
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
file.CopyTo(tempPath, false);
}
// If copying subdirectories, copy them and their contents to new location using recursive function.
if (isCopySubDirs)
{
foreach (DirectoryInfo item in directories)
{
string tempPath = System.IO.Path.Combine(destDirName, item.Name);
DirectoryCopy(item.FullName, tempPath, isCopySubDirs);
}
}
}
I can copy all the files from multiple directory's but what I want to do is copy all of the directory's with the files inside them as they are where I am copying the from and not putting just the files in my target folder. Here is my code so far
{
string SelectedPath = (string)e.Argument;
string sourceDirName;
string destDirName;
bool copySubDirs;
DirectoryCopy(".", SelectedPath, true);
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);
}
}
}
any help will be appreciated
There is no out of the box method for copying directories. The best you can do is use Extension methods. Have a look at this - http://channel9.msdn.com/Forums/TechOff/257490-How-Copy-directories-in-C/07964d767cc94c3990bb9dfa008a52c8
Here is the complete example (Just tested and it works):
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var di = new DirectoryInfo("C:\\SomeFolder");
di.CopyTo("E:\\SomeFolder", true);
}
}
public static class DirectoryInfoExtensions
{
// Copies all files from one directory to another.
public static void CopyTo(this DirectoryInfo source, string destDirectory, bool recursive)
{
if (source == null)
throw new ArgumentNullException("source");
if (destDirectory == null)
throw new ArgumentNullException("destDirectory");
// If the source doesn't exist, we have to throw an exception.
if (!source.Exists)
throw new DirectoryNotFoundException("Source directory not found: " + source.FullName);
// Compile the target.
DirectoryInfo target = new DirectoryInfo(destDirectory);
// If the target doesn't exist, we create it.
if (!target.Exists)
target.Create();
// Get all files and copy them over.
foreach (FileInfo file in source.GetFiles())
{
file.CopyTo(Path.Combine(target.FullName, file.Name), true);
}
// Return if no recursive call is required.
if (!recursive)
return;
// Do the same for all sub directories.
foreach (DirectoryInfo directory in source.GetDirectories())
{
CopyTo(directory, Path.Combine(target.FullName, directory.Name), recursive);
}
}
}
}
Have you taken a look at http://msdn.microsoft.com/en-us/library/bb762914.aspx ?
Maybe try to see if the path exists before the copy. If it isn't there, then create it?
string folderPath = Path.GetDirectoryName(path);
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
The smart way to do it is as in nithins answer. Using your approach you could use the FileInfo.Directory information to determine the source of the file and then create this directory in your destination if required. But nithins link is a cleaner solution.