I have program which writes to database which folders are full or empty. Now I’m using
bool hasFiles=false;
(Directory.GetFiles(path).Length >0) ? hasFiles=true: hasFiles=false;
but it takes almost one hour, and I can’t do anything in this time.
Is there any fastest way to check if folder has any file ?
The key to speeding up such a cross-network search is to cut down the number of requests across the network. Rather than getting all the directories, and then checking each for files, try and get everything from one call.
In .NET 3.5 there is no one method to recursively get all files and folders, so you have to build it yourself (see below). In .NET 4 new overloads exist to to this in one step.
Using
DirectoryInfoone also gets information on whether the returned name is a file or directory, which cuts down calls as well.This means splitting a list of all the directories and files becomes something like this:
Implementing
GetAllFileSystemObjectsdepends on the .NET version. On .NET 4 it is very easy:On earlier versions a little more work is needed:
This approach calls into the filesystem as few times as possible, just once on .NET 4 or once per directory on earlier versions, allowing the network client and server to minimise the number of underlying filesystem calls and network round trips.
Getting
FileSystemInfoinstances has the disadvantage of needing multiple file system operations (I believe this is somewhat OS dependent), but for each name any solution needs to know if it is a file or directory so this is not avoidable at some level (without resorting to P/Invoke ofFindFileFirst/FindNextFile/FindClose).Aside, the above would be easier with a partition extension method:
Writing that to be lazy would be an interesting exercise (only consuming input when something iterates over one of the outputs, while buffering the other).