我正在进行一个项目,想要将一个目录中的一些文件复制到一个已经存在的第二个目录中。
我找不到简单地从一个文件夹复制到另一个文件夹的方法。可以找到复制文件到新文件或目录到新目录的方法。
我目前设置程序的方式是将文件复制并留在同一个目录中,然后将该复制移动到我想要的目录。
编辑:
谢谢大家。你们所有人的答案都有效。我意识到我做错了什么,当我设置目标路径时,我没有添加文件名。现在一切都正常了,感谢超级迅速的回应。
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");
运行良好。
var fileName = "sourceFile.txt";
var source = Path.Combine(Environment.CurrentDirectory, fileName);
var destination = Path.Combine(destinationFolder, fileName);
File.Copy(source, destination);
这对我有用:
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));
}
File.Copy("c:\\myFolder\\myFile.txt", "c:\\NewFolder\\myFile.txt");
?
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 上
NET6 - 扩展方法
[DebuggerStepThrough]
public static FileInfo CopyToDir(this FileInfo srcFile, string destDir) =>
(srcFile == null || !srcFile.Exists) ? throw new ArgumentException($"The specified source file [{srcFile.FullName}] does not exist", nameof(srcFile)) :
(destDir == null || !Directory.Exists(destDir)) ? throw new ArgumentException($"The specified destination directory [{destDir}] does not exist", nameof(destDir)) :
srcFile.CopyTo(Path.Combine(destDir, srcFile.Name), true);
我使用了这段代码,它对我很有效
//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);
Path.Combine
来连接路径字符串。 - asdf