Retrieve all .doc files exist in My Computer for a search term which user provides. Is it possible?

StackOverflow https://stackoverflow.com/questions/22236122

Question

Retrieve all .doc files exist in My Computer using a search term which user provides. I have tried to query systemindex catlog and the problem is, it is not fetching the documents which is recently added.

My code is like below

SELECT "System.ItemName", "System.ItemFolderPathDisplay" FROM "SystemIndex" WHERE CONTAINS(*,'"searchterm"',1033) AND (System.FileName LIKE '%.doc' OR System.FileName LIKE '%.txt') AND Contains(System.Kind, 'document') ORDER BY System.FileName ASC

The problem with the above query is, it is not fetching instantly created files sometimes.

Was it helpful?

Solution 2

I would use .net's Directory class.

var files = Directory.GetFiles(path, "*.doc", SearchOptions.AllDirectories)
               .Where(m => m.Contains(yourSearchTerm));

That'll return all .doc files in the directory at the path you provide that contain the given search term. If its too slow I'd look into limiting it from running on the entire c drive.

More info about the Directory class can be found here

More info about Enumerable's Where method can be found here

Edit: To handle UnauthorizedAccessExceptions you need to do this recursively and check each directory individually so you can eat the exception if you don't have access to the current directory.

IEnumerable<string> SearchAccessibleFiles(string root, string searchTerm) {
    var files = new List<string>();

    foreach (var file in Directory.GetFiles(root)
                             .Where(m => m.Contains(searchTerm))) 
    {
        files.Add(file);
    }
    foreach (var subDir in Directory.GetDirectories(root)) {
        try {
            files.AddRange(GetAllAccessibleFiles(subDir, searchTerm));
        }
        catch (UnauthorizedAccessException ex) {
            // ...
        }
    }

    return files;
} 

And can be used like:

var files = GetAllAccessibleFiles(@"c:\", "bugs");

This will return every file in an accessible directory that contains the phrase "bugs" in the file name.

OTHER TIPS

I use the following code to get all .doc's on C:. It can be modified to search for a user specified string. You could just use this and then loop through filePaths, looking for your user specified string.

    string myPath = @"C:\";
    string[] filePaths = Directory.GetFiles(myPath, "*.doc",SearchOption.AllDirectories);

Edit: of course, this eliminates the need for a wmi query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top