C#:在foreach语句中使用Directory.GetFiles的副作用并删除文件?

mr_*_*org 1 c# file-io

我有以下foreach循环:

using System.IO;
//...   
if (Directory.Exists(path))
{
    foreach(string strFile in Directory.GetFiles(path, "*.txt"))
    {
        // do something, possibly delete the file named strFile
    }
}
Run Code Online (Sandbox Code Playgroud)

删除当前用于foreach循环的目录中的文件时是否会有副作用?

tva*_*son 9

GetFiles返回一个数组,而不是迭代器,因此在引用第一个文件时操作就完成了.它也只返回文件名,而不是文件句柄,所以你应该完全安全地对它进行任何操作.