问题
I am trying to clean up over 150K of files within a directory using .NET 3.5 and PowerShell. Since there are so many files I do not want to impact the server performance by reading everything in at once. Is there any mechanism with .NET 3.5 or PowerShell or methods accessible via PInvoke that would allow me to lazily load the files? Thank you for your assistance.
回答1:
If by "load" you mean to get a list of the files in a directory in a lazy manner, you have a couple of options.
As of .NET 4.0, you can use the new Directory.EnumerateFiles APIs to get a streaming (lazy) sequence of files in a particular directory. The search returns items on-demand, and so doesn't require as much memory as the existing GetFiles methods.
If you cannot use .NET 4, then you will have to roll your own streaming file enumerator. This would require using the FindFirstFile and FindNextFile Win32 APIs. However, you could take a look at this implementation on CodeProject, as it appears to be just that.
来源:https://stackoverflow.com/questions/4888836/enumeratefiles-equivalent-in-net-3-5