I am using Directory.GetFiles to find files that will be copied. I need to find the paths of the files so I can use copy, but I have no idea how to find the path.
It iterates through the files fine, but I can’t copy or move them because I need the file’s source path.
This is what I have:
string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
System.Console.WriteLine("Files Found");
// Display all the files.
foreach (string file in files)
{
string extension = Path.GetExtension(file);
string thenameofdoom = Path.GetFileNameWithoutExtension(file);
string filename = Path.GetFileName(file);
bool b = false;
string newlocation = (@"\\TEST12CVG\Public\Posts\Temporaryjunk\");
if (extension == ".pst" ||
extension == ".tec" ||
extension == ".pas" ||
extension == ".snc" ||
extension == ".cst")
{
b = true;
}
if (thenameofdoom == "Plasma" ||
thenameofdoom == "Oxygas" ||
thenameofdoom == "plasma" ||
thenameofdoom == "oxygas" ||
thenameofdoom == "Oxyfuel" ||
thenameofdoom == "oxyfuel")
{
b = false;
}
if (b == true)
{
File.Copy(file, newlocation + thenameofdoom);
System.Console.WriteLine("Success: " + filename);
b = false;
}
}
Path.GetFullPathworks, but also consider usingFileInfoas it comes with many file helper methods.I would use a method similar to this (could use a lot more error handling (try catches…) but it’s a good start
EDIT I noticed that you are filtering out the extensions, but requiring them, update to code allows for that
With a call like: