namespace Backup
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Backup_Click(object sender, EventArgs e)
{
List<DirectoryInfo> SourceDir = this.lbox_Sources.Items.Cast<DirectoryInfo>().ToList();
string TargetDir = this.tbox_Target.Text;
foreach (DirectoryInfo directory in SourceDir)
{
foreach (var file in directory.GetFiles())
File.Copy(file.Name, Path.Combine(TargetDir, file.Name), true);
}
}
当我尝试备份时,会抛出异常,但该文件存在且可访问。编程不是那么好,所以可能有一些愚蠢的错误:P
答案 0 :(得分:1)
好像你需要修改File.Copy
行:
var targetPath = Path.Combine(TargetDir, file.Name)
File.Copy(file.FullName, targetPath , true);
我将第一个参数从file.Name
更改为file.FullName
- 这应该可以修复异常
答案 1 :(得分:0)
用File.Copy中的file.FullName替换file.Name
foreach (var file in directory.GetFiles())
File.Copy(file.FullName, Path.Combine(TargetDir, file.Name), true);