【问题标题】:Count files, if it is one file then copy to another folder [closed]计算文件,如果是一个文件,则复制到另一个文件夹[关闭]
【发布时间】:2018-09-26 08:53:03
【问题描述】:

我已经计算了文件夹中有多少个文件。如果是 one 我想将该文件复制到另一个文件夹。我想将文件复制到另一个文件夹,但文件。 Copy 不接受 int。这是我的代码:

var path       = @"C:\Projects\Copy";
var fileType   = @"*.txt";
var fileOutput = @"C:\Projects\Paste";

int fCount = Directory.GetFiles(path, fileType).Length;

if (fCount == 1)
{
    File.Copy(fCount, fileOutput); // I get stuck here
}

【问题讨论】:

  • 你在哪里卡住了?您肯定已经搜索过如何将文件复制到另一个文件夹,您尝试了什么,什么不起作用?
  • How to copy a file in C#的可能重复
  • 使用这个 System.IO.File.Copy(s, destFile, true);
  • File.Move(srcFile, destFile);
  • 在此问题因不清楚而关闭之前,请尝试更准确地说明您要做什么。 “我想将文件复制到另一个文件夹但文件”这很难理解(至少对我来说)你为什么尝试将int 放入方法中?您对此次行动有何想法?

标签: c# file


【解决方案1】:

如果你想知道是否有只有一个文件:

 using System.IO;
 using System.Linq;

 ...

 // Directory.GetFiles returns all files found (e.g. 1234567 files) it can be very slow
 // we want at most 2 files found in order do not start copying:
 string[] files = Directory
   .EnumerateFiles(path, fileType) // not GetFiles
   .Take(2)                        // Take at most 2 files
   .ToArray();   

 // we can have 0, 1 or 2 files (thanks to Take(2)) 
 if (files.Length == 1)
   File.Copy(files[0], Path.Combine(fileOutput, Path.GetFileName(files[0])));

如果你想复制文件,如果有至少一个文件,我们可以跳过检查

 foreach (var file in Directory.EnumerateFiles(path, fileType))  
   File.Copy(file, Path.Combine(fileOutput, Path.GetFileName(file)));

请注意

Path.Combine(fileOutput, Path.GetFileName(file))

我们从目标目录原始文件名创建一个新的文件名。

【讨论】:

  • 你的代码给了我一个关于性能方面的扩展方法的想法。
  • 非常感谢德米特里。它的工作方式正是我想要的工作方式!
【解决方案2】:

试试File.Copy("C:\Projects\fileToCopy.txt", "C:\pathToNewLocation\copyOfMyFile.txt", true); 你必须给出File.Copy方法的路径而不是int

Documentation of File.Copy method

【讨论】:

    猜你喜欢
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多