I am trying to recursively get all of the files — 5 or 6 files give or take — under the directory C:\YC. I am bound to one WMI call to a remote computer.
I managed to do this call using the WQL LIKE operator but it's taking around 30 seconds, even though the result is around 6 files:
// USING A WQL QUERY
string query = "SELECT Name,LastModified FROM CIM_DataFile WHERE PATH LIKE '\\\\YC\\\\%' AND DRIVE ='C:'";
ObjectQuery oQuery = new ObjectQuery();
oQuery.QueryString = query;
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(scope, oQuery);
oSearcher.Options.Rewindable = false;
// Takes long time
ManagementObjectCollection oReturnCollection = oSearcher.Get();
// SHOWING EACH FILE
foreach (ManagementObject oReturn in oReturnCollection)
{
Console.WriteLine(oReturn["Name"]?.ToString());
}
Is there a more efficient way using System.Management objects to get the files recursively (with or without WQL, but with one WMI call)?
It seems that using WMI to query the filesystem is very slow when using the
LIKEoperator to filter on theName/Pathproperty, even if the filter value doesn't contain a wildcard (%).This will take more than one query, but you can get the
CIM_Directory(actuallyWin32_Directory) instance for your base directory and traverse the hierarchy yourself...That's calling
GetRelated()to get allCIM_LogicalFileinstances associated withdirectory;CIM_LogicalFileis the parent class ofCIM_DataFileandCIM_Directory, which itself is the parent ofWin32_Directory. We could call the simplerdirectory.GetRelated("CIM_LogicalFile")overload but that would return oneCIM_Directoryinstance we don't want: the parent directory. Instead, we call that longer overload that allows us to specify that we wantdirectoryto be the parent in theCIM_Directory⇔CIM_Directoryrelationship.You would call
EnumerateDirectory()like this...If you only want the immediate child files in a directory that code is much simpler...