I looking for an efficient way to list all files in the drives. The easy way would be to list files in C#:
static void Main(string[] args)
{
SearchFiles("C:\\", ".txt");
}
public void SearchFiles(string rootDir, string fileExtension)
{
SearchFilesRecursive(rootDir, fileExtension);
}
private void SearchFilesRecursive(string directory, string fileExtension)
{
try
{
foreach (string file in Directory.GetFiles(directory))
{
if (Path.GetExtension(file).Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine(file);
}
}
foreach (string subDir in Directory.GetDirectories(directory))
{
SearchFilesRecursive(subDir, fileExtension/*, foundFiles*/);
}
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.Message);
// Handle any unauthorized access exceptions here.
}
catch (DirectoryNotFoundException)
{
// Handle any directory not found exceptions here.
}
}
but this is a super slow way to do this. I came across Window Search Service. I wrote the following code which worked faster but I was only able to print files in C:/Users/{currentUser} directory. The code was not able read other folders in C: drive.
static void Main(string[] args)
{
var connection = new OleDbConnection(@"Provider=Search.CollatorDSO;Extended Properties=""Application=Windows""");
// get everything
var query1 = @"SELECT System.ItemUrl FROM SystemIndex";
connection.Open();
int counter = 0;
var command = new OleDbCommand(query1, connection);
using (var r = command.ExecuteReader())
{
while (r.Read())
{
Console.WriteLine(r[0]);
Console.WriteLine();
counter ++;
}
}
connection.Close();
Console.WriteLine($"Counter: {counter}");
Console.WriteLine("Searh Ended");
Console.ReadKey();
}
The wiki quoted
"The index store, called SystemIndex, contains all retrievable Windows IPropertyStore values for indexed items."
Why are other directories not retrievable using the above code? Can I access files in other directory using Window Search Service?