tags:

views:

1604

answers:

2

Hello,

I have 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 that is currently used for the foreach-loop?

+7  A: 

GetFiles returns an array, not an iterator so the operation is complete by the time you reference the first file. Also it only returns the file names, not a File handle so you should be completely safe doing any operation on it.

tvanfosson
+2  A: 

The enumerator doesnt requery on each hit so you should be fine - that said if a file shows up in the folder while you are in the process it will not get deleted.

keithwarren7