将文件复制到其他目录

时间:2011-09-18 17:04:25

标签: c# .net file

我正在开发一个项目,我希望将一个目录中的某些文件复制到另一个已存在的目录中。

我找不到简单地从一个文件夹复制到另一个文件夹的方法。我可以找到复制文件到新文件,或者目录到新目录。

我现在设置程序的方法是将文件复制并保存在同一目录中,然后将该副本移到我想要的目录中。

编辑:

谢谢大家。你的所有答案都有效。我意识到我做错了什么,当我设置目标路径时,我没有添加文件名。现在一切正常,感谢超级快速的回应。

7 个答案:

答案 0 :(得分:36)

string fileToCopy = "c:\\myFolder\\myFile.txt";
string destinationDirectory = "c:\\myDestinationFolder\\";

File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));

答案 1 :(得分:35)

File.Copy(@"someDirectory\someFile.txt", @"otherDirectory\someFile.txt");

工作正常。

答案 2 :(得分:15)

MSDN File.Copy

var fileName = "sourceFile.txt";
var source = Path.Combine(Environment.CurrentDirectory, fileName);
var destination = Path.Combine(destinationFolder, fileName);

File.Copy(source, destination);

答案 3 :(得分:7)

这对我有用:

    string picturesFile = @"D:\pictures";
    string destFile = @"C:\Temp\tempFolder\";

    string[] files = Directory.GetFiles(picturesFile);
    foreach (var item in files)
    {
       File.Copy(item, destFile + Path.GetFileName(item));
    }

答案 4 :(得分:6)

也许

File.Copy("c:\\myFolder\\myFile.txt", "c:\\NewFolder\\myFile.txt");

答案 5 :(得分:0)

如果目标目录不存在,将抛出File.Copy。这个版本解决了

public void Copy(
            string sourceFilePath,
            string destinationFilePath,
            string destinationFileName = null)
{
       if (string.IsNullOrWhiteSpace(sourceFilePath))
                throw new ArgumentException("sourceFilePath cannot be null or whitespace.", nameof(sourceFilePath));
       
       if (string.IsNullOrWhiteSpace(destinationFilePath))
                throw new ArgumentException("destinationFilePath cannot be null or whitespace.", nameof(destinationFilePath));
       
       var targetDirectoryInfo = new DirectoryInfo(destinationFilePath);

       //this creates all the sub directories too
       if (!targetDirectoryInfo.Exists)
           targetDirectoryInfo.Create();

       var fileName = string.IsNullOrWhiteSpace(destinationFileName)
           ? Path.GetFileName(sourceFilePath)
           : destinationFileName;

       File.Copy(sourceFilePath, Path.Combine(destinationFilePath, fileName));
}

在.NET Core 2.1上测试

答案 6 :(得分:-1)

我使用了这段代码,它对我有用

//I declare first my variables
string sourcePath = @"Z:\SourceLocation";
string targetPath = @"Z:\TargetLocation";

string destFile = Path.Combine(targetPath, fileName);
string sourceFile = Path.Combine(sourcePath, fileName);

// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

// To copy a file to another location and 
// overwrite the destination file if it already exists.
File.Copy(sourceFile, destFile, true);
相关问题