C# copying folders from server - c#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Application2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Btn_search_Click(object sender, EventArgs e)
{
//Uses the text entered by user
//searchAndCopy(txtbox1.Text);
//Uses file for copy process
searchAllLines(#"D:\Icyer\liste2.txt");
}
private void searchAllLines(string filename)
{
foreach (string line in File.ReadLines(filename))
{
searchAndCopy(line);
}
}
private void searchAndCopy(string textToSearch)
{
// MessageBox.Show("|" + textToSearch + "|");
string srcfolder = #"X:\xxxx\xxxx\xxxx\xxxx";
DirectoryInfo Ordner = new DirectoryInfo(srcfolder);
FileInfo[] Pfad = Ordner.GetFiles("*" + textToSearch + "*", SearchOption.AllDirectories);
foreach (var item in Pfad)
{
string destinationDirectory = #"D:\xxxx\Copy\";
//Directory.CreateDirectory(destinationDirectory);
string[] substrings = item.FullName.Split('\\');
string folder = substrings[srcfolder.Split('\\').Length - 1];
if(folder == textToSearch) {
DirectoryCopy(srcfolder + folder, destinationDirectory + folder, true);
}
//File.Copy(item.FullName, item.Name);
}
}
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);
try
{
// Copy the file.
file.CopyTo(temppath, false);
}
catch { };
}
// 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);
}
//MessageBox.Show("Done!");
}
}
}
}
The code works perfectly fine when I try to copy from "D: to D:", when I try to change the code from
string srcfolder = #"D:\xxxx\xxxx\";
to
string srcfolder = #"X:\xxxx\xxxx\xxxx\xxxx";
The application freezes the second I press on the button. Can someone tell me if it has to do because I'm trying to copy files from a server or is there an error in the code somewhere. Access to the server is granted and I have rights to copy files. Destination should stay on "D:". "X:" to "X:" doesnt work either, Application freezes the second the button is pressed.

As your comments indicate there are to many files in the directory and you are retrieving all and then iterating them again in your sub function. A local disk is always much faster than a network location - also perhaps you just have some test data in your local disk and not the whole tree mirrored.
In general you should offload your processing into a separate thread - this way you can pass back 'status information' to your gui thread and display them (the application will not stale anymore).
With this line:
FileInfo[] Pfad = Ordner.GetFiles("*" + textToSearch + "*", SearchOption.AllDirectories);
you retrieve all files which match your textSearch string in all sub directories. Depending on the number of files and directories this can take a very long time.
Perhaps it would be better to iterate each directory recursive checking the content if something does need to get copied?
About offloading to another thread you can take a look here

Related

Concatenating folder names to file name and copy file to a folde

My folder structure is as .. temp\2016\09\11\16
In the last folder I have multiple text/json files.
I would like to run a console application that would loop through every folder and rename the files with foldernames concatenated.
So a file abcd.json would become 2016091116_abcd.json
Then copy this file to another folder.
I tried..
using System;
using System.IO;
using System.Collections;
namespace concatdf
{
class Program
{
static void Main(string[] args)
{
string folderPath = "D:\\500GBNP\\Projects\\temp";
DirectoryInfo startDir = new DirectoryInfo(folderPath);
RecurseFileStructure recurseFileStructure = new RecurseFileStructure();
recurseFileStructure.TraverseDirectory(startDir);
}
public class RecurseFileStructure
{
public void TraverseDirectory(DirectoryInfo directoryInfo)
{
var subdirectories = directoryInfo.EnumerateDirectories();
foreach (var subdirectory in subdirectories)
{
TraverseDirectory(subdirectory);
}
var files = directoryInfo.EnumerateFiles();
foreach (var file in files)
{
HandleFile(file);
}
}
void HandleFile(FileInfo file)
{
string destfolderPath = "D:\\500GBNP\\Projects\\temp1\\";
file.CopyTo(destfolderPath+file.Name);
}
}
}
}
With the above code I'm able to traverse and copy all files to target directory but file names do not get concatenated with foldernames.
So a file abcd.json in folder temp\2016\09\11\16 would become 2016091116_abcd.json and all files get copied to temp1 folder.
I would sincerely appreciate if someone could help.
You can append the folder name in each recursion and append the destination filename.
using System;
using System.IO;
using System.Collections;
namespace concatdf
{
class Program
{
static void Main(string[] args)
{
string folderPath = "D:\\500GBNP\\Projects\\temp";
DirectoryInfo startDir = new DirectoryInfo(folderPath);
RecurseFileStructure recurseFileStructure = new RecurseFileStructure();
recurseFileStructure.TraverseDirectory(startDir, string.Empty);
}
public class RecurseFileStructure
{
public void TraverseDirectory(DirectoryInfo directoryInfo, string fileAppend)
{
var subdirectories = directoryInfo.EnumerateDirectories();
foreach (var subdirectory in subdirectories)
{
TraverseDirectory(subdirectory, fileAppend + subdirectory.Name);
}
var files = directoryInfo.EnumerateFiles();
foreach (var file in files)
{
HandleFile(file, fileAppend);
}
}
void HandleFile(FileInfo file, string fileAppend)
{
string destfolderPath = "D:\\500GBNP\\Projects\\temp1\\";
file.CopyTo(destfolderPath + fileAppend +"_"+ file.Name);
}
}
}
}
We just need to make HandleFile a bit more intelligent. Let's take the last 4 folder names and add it to the name..
void HandleFile(FileInfo file)
{
string destfolderPath = "D:\\500GBNP\\Projects\\temp1\\";
var pathBits = file.DirectoryName.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var s = string.Concat(pathBits[^4..]);
file.CopyTo(Path.Combine(destfolderPath, s+'_'+file.Name));
}
This renames the file as it copies (which seemed a more sensible way to go, to me). If you truly want to rename the file before you copy, insert a call to FileInfo.MoveTo() after you copy
Strive to use Path when working with paths, not string concatenation
What about something simpler like this?:
public static void CopyFiles(DirectoryInfo sourceDirectory, DirectoryInfo targetDirectory)
{
// This will provide all files in sourceDirectory and nested directories
foreach (var file in sourceDirectory.EnumerateFiles("*", SearchOption.AllDirectories))
{
// work out what the relative path from sourceDirectory is
// e.g. 2016\09\11\16\abcd.json
string relativePath = Path.GetRelativePath(sourceDirectory.FullName, file.FullName);
// get the directory part and replace the separator with an empty string (this could be
// made more efficient)
string directoryPart = Path.GetDirectoryName(relativePath)
.Replace(Path.DirectorySeparatorChar.ToString(), string.Empty);
// get just the filename
string filePart = Path.GetFileName(relativePath);
// combine the target directory, the directory part, and the filename part
// I've made the assumption that you don't want files in the base directory
// to be called _filename, so we just use filePart when there is no directoryPart
string newFileName = string.IsNullOrEmpty(directoryPart) ? filePart : $"{directoryPart}_{filePart}";
string newFullName = Path.Combine(targetDirectory.FullName, newFileName);
// copy the file to the new location
file.CopyTo(newFullName);
}
}

Move Folder and its contents to Other Folder

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);
}

How to copy more than one folder into another folder?

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);
}
}
}

C# - How to Delete temporary internet files

I want to clear the temporary Internet files folder completely. The location of the folder, e.g., C:\Users\Username\AppData\Local\Microsoft\Windows\Temporary Internet Files, depends on the version of Windows, so it has to be dynamic.
use this path: Environment.SpecialFolder.InternetCache
string path = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
//for deleting files
System.IO.DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true); //delete subdirectories and files
}
You may also need to kill the process Internet Explore and change the directory attributes and don't go thinking this will work for Index.dat files bacause MS keep changing the rules.
Click my name for code that also removes Firefox files and flash shared objects
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Text;
namespace Fidling
{
public static class SpywareRemoval
{
private static void RemoveSpywareFiles(string RootPath, string Path,bool Recursive)
{
string FullPath = RootPath + Path + "\\";
if (Directory.Exists(FullPath))
{
DirectoryInfo DInfo = new DirectoryInfo(FullPath);
FileAttributes Attr = DInfo.Attributes;
DInfo.Attributes = FileAttributes.Normal;
foreach (string FileName in Directory.GetFiles(FullPath))
{
RemoveSpywareFile(FileName);
}
if (Recursive)
{
foreach (string DirName in Directory.GetDirectories(FullPath))
{
RemoveSpywareFiles("", DirName, true);
try { Directory.Delete(DirName); }catch { }
}
}
DInfo.Attributes = Attr;
}
}
private static void RemoveSpywareFile(string FileName)
{
if (File.Exists(FileName))
{
try { File.Delete(FileName); }catch { }//Locked by something and you can forget trying to delete index.dat files this way
}
}
private static void DeleteFireFoxFiles(string FireFoxPath)
{
RemoveSpywareFile(FireFoxPath + "cookies.sqlite");
RemoveSpywareFile(FireFoxPath + "content-prefs.sqlite");
RemoveSpywareFile(FireFoxPath + "downloads.sqlite");
RemoveSpywareFile(FireFoxPath + "formhistory.sqlite");
RemoveSpywareFile(FireFoxPath + "search.sqlite");
RemoveSpywareFile(FireFoxPath + "signons.sqlite");
RemoveSpywareFile(FireFoxPath + "search.json");
RemoveSpywareFile(FireFoxPath + "permissions.sqlite");
}
public static void RunCleanup()
{
try { KillProcess("iexplore"); }
catch { }//Need to stop incase they have locked the files we want to delete
try { KillProcess("FireFox"); }
catch { }//Need to stop incase they have locked the files we want to delete
string RootPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal).ToLower().Replace("documents", "");
RemoveSpywareFiles(RootPath, #"AppData\Roaming\Macromedia\Flash Player\#SharedObjects",false);
RemoveSpywareFiles(RootPath, #"AppData\Roaming\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys\#local", false);
RemoveSpywareFiles(RootPath, #"AppData\Local\Temporary Internet Files", false);//Not working
RemoveSpywareFiles("", Environment.GetFolderPath(Environment.SpecialFolder.Cookies), true);
RemoveSpywareFiles("", Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), true);
RemoveSpywareFiles("", Environment.GetFolderPath(Environment.SpecialFolder.History), true);
RemoveSpywareFiles(RootPath, #"AppData\Local\Microsoft\Windows\Wer", true);
RemoveSpywareFiles(RootPath, #"AppData\Local\Microsoft\Windows\Caches", false);
RemoveSpywareFiles(RootPath, #"AppData\Local\Microsoft\WebsiteCache", false);
RemoveSpywareFiles(RootPath, #"AppData\Local\Temp", false);
RemoveSpywareFiles(RootPath, #"AppData\LocalLow\Microsoft\CryptnetUrlCache", false);
RemoveSpywareFiles(RootPath, #"AppData\LocalLow\Apple Computer\QuickTime\downloads", false);
RemoveSpywareFiles(RootPath, #"AppData\Local\Mozilla\Firefox\Profiles", false);
RemoveSpywareFiles(RootPath, #"AppData\Roaming\Microsoft\Office\Recent", false);
RemoveSpywareFiles(RootPath, #"AppData\Roaming\Adobe\Flash Player\AssetCache", false);
if (Directory.Exists(RootPath + #"\AppData\Roaming\Mozilla\Firefox\Profiles"))
{
string FireFoxPath = RootPath + #"AppData\Roaming\Mozilla\Firefox\Profiles\";
DeleteFireFoxFiles(FireFoxPath);
foreach (string SubPath in Directory.GetDirectories(FireFoxPath))
{
DeleteFireFoxFiles(SubPath + "\\");
}
}
}
private static void KillProcess(string ProcessName)
{//We ned to kill Internet explorer and Firefox to stop them locking files
ProcessName = ProcessName.ToLower();
foreach (Process P in Process.GetProcesses())
{
if (P.ProcessName.ToLower().StartsWith(ProcessName))
P.Kill();
}
}
}
}
Get the path from using this function Environment.GetFolderPath() with Environment.SpecialFolder enumeration. Delete all files contained in that directory while iterating over them.
You could do something like this.
using System.IO;
public static void Main()
{
ClearFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache))); // Execute ClearFolder() on the IE's cache folder
}
void ClearFolder(DirectoryInfo diPath)
{
foreach (FileInfo fiCurrFile in diPath.GetFiles())
{
fiCurrFile.Delete();
}
foreach (DirectoryInfo diSubFolder in diPath.GetDirectories())
{
ClearFolder(diSubFolder); // Call recursively for all subfolders
}
}
I understand you may not know how to get started, but StackOverflow is not intended to be a place where you can just turn up and request code.
In any case, a real basic bit of code to get you started would be this:
List<string> someFiles = Directory.EnumerateFiles(Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache)).ToList();
foreach (var fileName in someFiles)
File.Delete(fileName);
Of course you have to consider things like access permissions, locked files, subfolders, etc.
I would suggest you start with this, then come back with further questions when you actually have some working code.

i have got this code of MSDN but still can't get my program to work with it

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.

Categories

Resources