4

I am trying to copy all format file (.txt,.pdf,.doc ...) file from source folder to destination.

I have write code only for text file.

What should I do to copy all format files?

My code:

string fileName = "test.txt";
string sourcePath = @"E:\test222";
string targetPath =  @"E:\TestFolder"; 

string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);

Code to copy file:

System.IO.File.Copy(sourceFile, destFile, true);
Omar
  • 16,329
  • 10
  • 48
  • 66
swapnil
  • 323
  • 2
  • 6
  • 13
  • Possible duplicate of [Copy Folders in C# using System.IO](http://stackoverflow.com/questions/677221/copy-folders-in-c-sharp-using-system-io) – Omar Jun 07 '12 at 08:12

3 Answers3

10

Use Directory.GetFiles and loop the paths

string sourcePath = @"E:\test222";
string targetPath =  @"E:\TestFolder";

foreach (var sourceFilePath in Directory.GetFiles(sourcePath))
{
     string fileName = Path.GetFileName(sourceFilePath);
     string destinationFilePath = Path.Combine(targetPath, fileName);   

     System.IO.File.Copy(sourceFilePath, destinationFilePath , true);
}
jflood.net
  • 2,446
  • 2
  • 21
  • 19
  • @jflood.net: vote down because initially you write only Directory.GetFiles(sourcePath). But, i am not that person :) – Talha Jun 07 '12 at 09:15
7

I kinda got the impression you wanted to filter by extension. If so, this will do it. Comment out the parts I indicate below if you don't.

string sourcePath = @"E:\test222";
string targetPath =  @"E:\TestFolder"; 

var extensions = new[] {".txt", ".pdf", ".doc" }; // not sure if you really wanted to filter by extension or not, it kinda seemed like maybe you did. if not, comment this out

var files = (from file in Directory.EnumerateFiles(sourcePath)
             where extensions.Contains(Path.GetExtension(file), StringComparer.InvariantCultureIgnoreCase) // comment this out if you don't want to filter extensions
             select new 
                            { 
                              Source = file, 
                              Destination = Path.Combine(targetPath, Path.GetFileName(file))
                            });

foreach(var file in files)
{
  File.Copy(file.Source, file.Destination);
}
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
2
string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories);

use this, and loop through all the files to copy into destination folder

Talha
  • 18,898
  • 8
  • 49
  • 66