C #: side effects with Directory.GetFiles in foreach statement and deleting files?

I have the following foreach loop:

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

      

Could there be side effects when deleting files in the directory currently being used for the foreach loop?

+1


source to share


2 answers


GetFiles returns an array, not an iterator, so the operation completes by the time you reference the first file. Also, it returns filenames, not a file descriptor, so you should be absolutely safe when performing any operation on it.



+9


source


The enumerator doesn't ask on every hit, so you should be fine - if the file is said to appear in the folder during the process, it won't be deleted.



+2


source







All Articles