C# FileInfo 移动 foreach

C# FileInfo move foreach

我有这个代码:

FileInfo finfo = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "backup", file.Key)); 
var fsize = finfo.Length;

if (fsize != file.Value)
{
    DialogResult modifiedcleofiles = MessageBox.Show("Oops! Modified files found! Click OK to move them!", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); 
    if(modifiedcleofiles == DialogResult.OK)
    {
        foreach (FileInfo filemove in finfo)
        {
            finfo.MoveTo(Path.Combine(Directory.GetCurrentDirectory(), "backup", filemove.Name));
        }
     }
     return;
}

但是 foreach 出错了,我该如何解决?

P.S 我收到这个错误:

foreach statement does not work with variables of type System.IO.FileInfo

如果您想迭代目录中的多个项目,您需要 DirectoryInfo,而不是 FileInfo 对象。

假设要获取finfo目录下的所有文件,代码应该是这样的:

foreach (FileInfo filemove in finfo.Directory.EnumerateFiles()) {
    ...
}

finfo.Directory gives you DirectoryInfo for finfo's directory, and EnumerateFiles() 可让您在 foreach 循环中查看其内容。