c# - Is it safe to delete or move while enumerating the file system? -
is safe delete or move files or directories when using directory.enumeratefiles
?
something this:
foreach (var filename in directory.enumeratefiles("sub")) file.delete(filename);
i know that, in general, not supposed modify you're enumerating. however, file system doesn't seem following rule since code above works.
the same question applies enumeratedirectories
, enumeratefilesystementries
, equivalent methods of directoryinfo
class.
yes can safely delete current file during such enumeration (at least on windows). directory.enumeratefiles
implemented internally (on windows) via findfirstfile , findnextfile winapi calls. first findfirstfile
called , on each iterator advance (movenext()
) - findnextfile
called. if file removed between calls - it's not problem api, findnextfile
return next matching file. in case delete current file nothing skipped @ all. if new file added in middle of enumeration - depends on it's name if included or not. got files "b.txt" , "c.txt" , file "a.txt" added. such file not included using directory.enumeratefiles
, because it's name "less" (in sense) files enumerated. return order not simple (depends on filesystem) got idea.
Comments
Post a Comment