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

3 回答 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);
}
于 2012-06-07T07:54:45.213 回答
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);
}
于 2012-06-07T08:05:51.870 回答
2
string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories);

使用它,并遍历所有文件以复制到目标文件夹

于 2012-06-07T07:59:18.970 回答