Copy entire format file format from folder in c #

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

I have code to write for a text file only.

What should I do to copy all format files?

My code is:

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 for copying the file:

 System.IO.File.Copy(sourceFile, destFile, true); 
+4
source share
3 answers

Use Directory.GetFiles and encode 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); } 
+10
source
 string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories); 

use this and skip all files to copy to destination folder

+2
source

I got the impression that you want to filter by extension. If so, it will do it. Please comment on the parts below if you do not.

 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
source

Source: https://habr.com/ru/post/1416521/


All Articles