我正在寻找一种方法,使用C#将文件从一个目录移动到另一个目录.我有一个表单应用程序,我希望用户使用文件选择器选择一个文件,并在单击"设置背景"按钮时将文件传输到应用程序中指定的位置.
在尝试@VulgarBinary提供的答案后,我得到以下异常:
System.IO.IOException: Cannot create a file when that file already exists.
Run Code Online (Sandbox Code Playgroud)

您需要确保您的程序具有编写文件的适当权限,但是:
if (File.Exists(sourcePath))
{
File.Move(sourcePath, destinationPath);
}
Run Code Online (Sandbox Code Playgroud)
这应该可以做你想做的事情.
例:
var sourcePath = "C:\Users\someuser\Pictures\VulgarBinary.jpg";
var destinationPath = "C:\Whatever\Path\You\Want\VulgarBinary.jpg";
Run Code Online (Sandbox Code Playgroud)
编辑1
鉴于您在此答案下方的评论,您遇到的问题是您正在创建的文件已存在.如果你想替换它,你可以简单地做:
if (File.Exists(sourcePath))
{
if(File.Exists(destinationPath))
File.Delete(destinationPath);
File.Move(sourcePath, destinationPath);
}
Run Code Online (Sandbox Code Playgroud)
如果您不关心输出文件的名称是什么,并且总是想要写它,您可以执行以下操作:
var outputDirectory = "C:\\Whatever\\Path\\You\\Want\\";
if (File.Exists(sourcePath))
{
File.Move(sourcePath, outputDirectory + Guid.NewGuid().ToString() + ".jpg");
}
Run Code Online (Sandbox Code Playgroud)
后者将始终复制文件(所有人都使用不同的名称).第一个解决方案将使用新文件替换任何具有相同名称的文件.
干杯!