从c#中的文件夹中复制所有类型格式文件

swa*_*nil 4 c#

我试图将所有格式文件(.txt,.pdf,.doc ...)文件从源文件夹复制到目标.

我只为文本文件编写代码.

我该怎么做才能复制所有格式文件?

我的代码:

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);
Run Code Online (Sandbox Code Playgroud)

复制文件的代码:

System.IO.File.Copy(sourceFile, destFile, true);
Run Code Online (Sandbox Code Playgroud)

jfl*_*net 10

使用Directory.GetFiles并循环路径

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);
}
Run Code Online (Sandbox Code Playgroud)


Hac*_*ese 5

我有点印象你想按扩展名过滤。如果是这样,这将做到。如果没有,请注释掉我在下面指出的部分。

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);
}
Run Code Online (Sandbox Code Playgroud)