从文件夹中复制所有类型格式的文件(C#)

4

我试图将源文件夹中的所有格式的文件(.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);

复制文件的代码:

System.IO.File.Copy(sourceFile, destFile, true);

可能是[使用System.IO在C#中复制文件夹]的重复问题(https://dev59.com/dnRB5IYBdhLWcg3wQVSV)。 - Omar
3个回答

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

@jflood.net:投反对票是因为你最初只写了Directory.GetFiles(sourcePath)。但是,我不是那个人 :) - Talha

7

我有点感觉你想按扩展名过滤。如果是这样,这个代码可以实现。如果不需要,请注释掉我下面指出的部分。

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

使用此方法,并循环遍历所有文件以复制到目标文件夹。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接