copy multiple files from listbox to specified folder - c#

there are in the files of my listbox ı want copy files these specified path for example c:\ or any path but error be (value cannot be null parameter name path) error how ı can copy specified path ı wirte this code
string source, fileToCopy, target;
string sourcefolder1;
string destinationfolder;
DirectoryInfo di = new DirectoryInfo(destinationfolder);
FileInfo[] annfiles;
foreach (string s in listBox1.Items)
{
fileToCopy = s;
source = Path.Combine(sourcefolder1, fileToCopy);
target = Path.Combine(destinationfolder, fileToCopy);
File.Copy(source, target);
annFiles = di.GetFiles();
}

I think the problem is here:
string destinationfolder;
You declare an empty string and after try to get DirectoryInfo from what? And Empty string? This thrown an Exception. You can see your code like this:
DirectoryInfo di = new DirectoryInfo("");
This code throw always an Exception.
The question is: what you need in "destinationFolder" parameter?
This is a sample file copy:
string sourceFolder = #"C:\Documents";
string destinationFolder = "#"C:\MyDocumentsCopy";
DirectoryInfo directory = new DirectoryInfo(sourceFolder);
FileInfo[] files = directory.GetFiles();
foreach(var file in files)
{
string destinationPath = Path.Combine(destinationFolder, file.Name);
File.Copy(file.Fullname, destinationPath);
}

Related

Copy files containing a name from source to destination c#

I have a list of Strings with a series of names, I want to find these names in the source directory and copy them to the destination.
This is what I am trying but with this I copy all source directory in target directory:
List<string> ncs = new List<string>();
ncs = getNames();
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(sourceDir))
CopyNCfromTo(directory, Path.Combine(targetDir, Path.GetFileName(directory)));
I am trying in this way too:
List<string> ncs = new List<string>();
ncs = getNames();
for (int i = 0; i < ncs.Count; i++)
{
FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles(ncs[i].ToString());
}
I thought to loop the list and the look for every file in the source folder, how could I do this?
I assume that the ncs list containing only names not the file path or the file name with extension.
foreach (var file in Directory.GetFiles(sourceDir))
if (ncs.Contains(Path.GetFileName(file).Split('.').First()))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)));
This is happening because foreach is browsing the files contained in the folder and not the list of names, that way, all files are copied to the destination folder.
foreach(string fileName in ncs){
string path = sourceDir + fileName;
bool result = System.IO.File.Exists(path);
if(result == true){
string destinationPath = targetDir + fileName;
System.IO.File.Copy(path,destinationPath);
}
}
That way you go through the list of names and check if the file exists, if it exists, copy the file to the destination folder
You can iterate over ncs, build the source and destination paths, and do a copy if the file exists.
Caveat: File.Exists() can introduce a race condition. If you are not confident no other process is working in that folder then you should handle IO exceptions.
string sourceDir = "C:\\....";
string targetDir = "C:\\....";
foreach (string filename in ncs)
{
string srcFile = Path.Combine(sourceDir, filename);
string destFile = Path.Combine(targetDir, filename);
if (File.Exists(srcFile))
{
File.Copy(srcFile, destFile);
}
}

How can I find a file within any description of path?

I need find the specific file/folder on my hard drive.
For example i need find a file (do1.bat) and then store the path of the file. But i dont know where can it be stored, so i have to scan all hard drive.
How can i use C# for this?
A simple way would be
var results = Directory.GetFiles("c:\\", "do1.bat", SearchOption.AllDirectories);
This would recurse through all directory and collect all files named do1.bat. Unfortunatly this will not work on complete c:\ since it will throw exceptions if you don't have access to a directory, which surely will happen.
So this is a recursive version:
private static void FindFile(DirectoryInfo currentDirectory, string pattern, List<FileInfo> results)
{
try
{
results.AddRange(currentDirectory.GetFiles(pattern, SearchOption.TopDirectoryOnly));
foreach (DirectoryInfo dir in currentDirectory.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => d.Name != "." && d.Name != ".."))
FindFile(dir, pattern, results);
}
catch
{
// probably no access to directory
}
}
This recurses through the directory tree and tries to get the files in a directory and then all subdirectories (except . and ..).
You can use it this way:
DirectoryInfo d = new DirectoryInfo("c:\\");
List<FileInfo> results = new List<FileInfo>();
FindFile(d, "do1.bat", results);
This will find all files named do1.bat in any subdirectory of C:\\ and enlist the FileInfos in the results list.
this should provide you a list of files, matching your search pattern
string[] Result = Directory.GetFiles(#"C:\", "do1.bat", SearchOption.AllDirectories);
Refer: https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx
List<string> lstfilepaths = new List<string>();
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries) // included as per your logic
{
if(fileName == "do1.bat")
{
ProcessFile(fileName);
}
}
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static void ProcessFile(string path)
{
lstfilepaths.Add(path);
}
For one file:
public string FindFileByName(string fileName, string searchPath)
{
string resultPath = null;
DirectoryInfo directoryInWhichToSearch = new DirectoryInfo(searchPath);
FileInfo foundFile = directoryInWhichToSearch.GetFiles(fileName, SearchOption.AllDirectories)[0];
resultPath = foundFile.FullName;
return resultPath;
}
You can then use it like this:
string fileFullPath = FindFileByName("do1.bat", #"C:\");

Remove sub-path of File name and create file structure

I have following List<String> fileNames getting passed to my method,
I want to remove the sub-path from that and create the left out file structure
string subPath = "C:\\temp\\test"
List<string> filesIncoming = new List[]{#"C:\temp\test\a.txt", #"C:\temp\test\intest\a.txt"};
string outputDir = "C:\\temp3\\temp";
Output should be:
C:\\temp3\temp\a.txt
C:\\temp3\temp\intest\a.txt
This is what I am trying
foreach (var file in files)
{
var directory = Path.GetDirectoryName(file);
DirectoryInfo source = new DirectoryInfo(directory);
var fileName = Path.GetFileName(file);
var destDir = Path.Combine(destinatonFilePath, source.Name); //how do I remove sub-path from source.Name and combine the paths properly?
CreateDirectory(new DirectoryInfo(destDir));
File.Copy(file, Path.Combine(destDir, fileName), true);
}
I think you should use the old good string.Replace to remove the common base path from your incoming files and replace it with the common base path for the output files
string subPath = "C:\\temp\\test"
string outputDir = "C:\\temp3\\temp";
foreach (var file in files)
{
// Not sure how do you have named these two variables.
string newFilePath = file.Replace(subPath, outputDir);
Directory.CreateDirectory(Path.GetDirectoryName(newFilePath));
File.Copy(file, newFilePath, true);
}

How to create a same directory as source copying a file in c#

I am copying file from my server.map path to some folder in C:\ But When i am copying my file i want that it create the folder path same it is in server.map path with file to copy
Here is my code where i am copying file but it is not creating the same directory which i want.
public void CopyFiles()
{
string Filename = "PSK_20150318_1143342198885.jpg";
string sourcePath = Server.MapPath("~/UserFiles/Images/croppedAvatar/");
string targetPath = #"C:\MyCopyFIle\";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath,Filename);
string destFile = System.IO.Path.Combine(targetPath,Filename);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// 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);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Debug.WriteLine("Source path does not exist!");
}
}
Now the source path contain /userfiles/images/croppedavatar directory in it when I am copying it in c:\MyCopyFile I want it create a folder structure like c:\MyCopyFile\UserFile\Images\CroppedAvatar
you have to check each file structure and create the same on destination and then copy file as
public void CopyFiles(string srcpath, List<string> sourcefiles, string destpath)
{
DirectoryInfo dsourceinfo = new DirectoryInfo(srcpath);
if (!Directory.Exists(destpath))
{
Directory.CreateDirectory(destpath);
}
DirectoryInfo dtargetinfo = new DirectoryInfo(destpath);
List<FileInfo> fileinfo = sourcefiles.Select(s => new FileInfo(s)).ToList();
foreach (var item in fileinfo)
{
string destNewPath = CreateDirectoryStructure(item.Directory.FullName, destpath) + "\\" + item.Name;
File.Copy(item.FullName, destNewPath);
}
}
public string CreateDirectoryStructure(string newPath, string destPath)
{
Queue<string> queue = new Queue<string>(newPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries));
queue.Dequeue();
while (queue.Count>0)
{
string dirName = queue.Dequeue();
if(!new DirectoryInfo(destPath).GetDirectories().Any(a=>a.Name==dirName))
{
Directory.CreateDirectory(destPath + "\\" + dirName);
destPath += "\\" + dirName;
}
}
return destPath;
}
You can simply create a folder structure using FileInfo Class:
string path=#"c:/MyCopyFile/UserFile/Images/CroppedAvatar/";
FileInfo file = new FileInfo(path);
file.Directory.Create();
This will create a directory where you can copy what you want to.
You can change your code like following
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)
{
Filename = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, Filename);
string path = #"C:/MyCopyFile/UserFiles/Images/croppedAvatar/";
FileInfo file = new FileInfo(path);
file.Directory.Create();
string folderStructurePath = #"C:/MyCopyFile/UserFiles/Images/croppedAvatar/" + Filename;
System.IO.File.Copy(sourceFile, folderStructurePath, 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);
}
}
}

Categories

Resources