繁体   English   中英

将文件复制到其他目录

[英]Copy file to a different directory

我正在处理一个项目,我想将一个目录中的一些文件复制到第二个已经存在的目录中。

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

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

编辑:

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

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

File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));
File.Copy(@"someDirectory\someFile.txt", @"otherDirectory\someFile.txt");

工作正常。

MSDN File.Copy

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

File.Copy(source, destination);

可能是

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

?

这对我有用:

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

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

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

如果目标目录不存在, 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 上测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM