【问题标题】:copy all type format file from folder in c#从C#中的文件夹复制所有类型格式文件
【发布时间】:2012-06-07 07:51:43
【问题描述】:

我正在尝试将所有格式文件(.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);

【问题讨论】:

标签: c#


【解决方案1】:

使用 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)。但是,我不是那个人:)
【解决方案2】:

我有点想通过扩展来过滤的印象。如果是这样,这将做到这一点。如果您不这样做,请注释掉我在下面指出的部分。

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

【讨论】:

    【解决方案3】:
    string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories);
    

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

    【讨论】:

      猜你喜欢
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 2016-08-04
      相关资源
      最近更新 更多