0

I am trying to copy all PDF files (.pdf) from the source folder to the destination. I have written it using a foreach loop, but I want to do it without for or any loop. Is there a way to do that, and if so, how?

My Code

string sourcePath = @"D:\DataArchiveTest\From";
string targetPath = @"D:\DataArchiveTest\To";
foreach (var sourceFilePath in Directory.GetFiles(sourcePath))
{
    string fileName = Path.GetFileName(sourceFilePath);
    string destinationFilePath = Path.Combine(targetPath, fileName);
    if (fileName.ToUpper().Contains(".PDF"))
    {
        System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
    }
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Md Aslam
  • 149
  • 3
  • 4
  • 11
  • Possible duplicate of [Best way to copy the entire contents of a directory in C#](http://stackoverflow.com/questions/58744/best-way-to-copy-the-entire-contents-of-a-directory-in-c-sharp) – Mostafiz May 04 '16 at 04:47
  • Actually the sourceFolder may contain thousands of files. If we use for loop then it affect the performance in my application – Md Aslam May 04 '16 at 04:55

4 Answers4

2

you can do something like this:

string sourcePath = @"D:\DataArchiveTest\From";
string targetPath = @"D:\DataArchiveTest\To";

var dir = new DirectoryInfo(sourcePath);
FileInfo[] files = dir.GetFiles("*.pdf");

foreach (var item in files)
{
   File.Copy(item.FullName, Path.Combine(targetPath, item.Name), true); // overwrite = true 
}
SᴇM
  • 7,024
  • 3
  • 24
  • 41
1

try filter before copy:

var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories)
                .Where(s => s.EndsWith(".pdf") );

refer : Can you call Directory.GetFiles() with multiple filters?

Community
  • 1
  • 1
D T
  • 3,522
  • 7
  • 45
  • 89
0

Since you mentioned in the comments, source directory has lot of files and you want to limit this to Pdf files alone (to gain performance), you could use an overloaded Directory.GetFiles allow you to specify search pattern.

Directory.GetFiles(sourcePath, "*.pdf"); 

Now we can you simplify your code to

string sourcePath = @"D:\DataArchiveTest\From";
string targetPath = @"D:\DataArchiveTest\To";
foreach (var sourceFilePath in Directory.GetFiles(sourcePath, "*.pdf"))
{
        string fileName = Path.GetFileName(sourceFilePath);
        string destinationFilePath = Path.Combine(targetPath, fileName);
        System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
}
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

I would do something like this:

string target = @"D:\DataArchiveTest\To\";
string source = @"D:\DataArchiveTest\From\";

string[] files = Directory.GetFiles(source, ".*pdf", SearchOption.AllDirectories);

foreach (string item in files)
{
    //Add try - catch
    File.Copy(item, target + item.Replace(source, ""),true);
}

Make sure you include a '\' at the end of your source path

Jan Wiesemann
  • 455
  • 2
  • 16