4
votes

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);
3
Possible duplicate of Copy Folders in C# using System.IOOmar

3 Answers

10
votes

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

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);
}
2
votes
string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories);

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