FileNotFoundException但文件存在C#

时间:2017-03-28 07:41:58

标签: c# backup

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

2 个答案:

答案 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);