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);
}
}
}
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 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);
}
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
Follow This Structure.
A
A1
A111
A2
A3
A4
B
My Source Address is: E:\A\A2
My Destination Address is E:\B
I want to Copy A2 in B where A2 is Empty.
If I use Code
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
string vSourceDirName = dir.Name;
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,vSourceDirName,subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
This Code is from msdn
How Can I Copy this Empty Folder in C#
Blockquote
You could use the function DirectoryCopy().
Using your example try DirectoryCopy (#"E:\A\A2", #"E:\B", true) and you will get E:\B\A2 created.
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);
}
}
}