2

I want to search the media files situated in my system by c#. means I want to create the search engine that will scan all drives (again small question here , how to get the drives on our system by c# code ? )and search the media files like .mp3,.mp4,...etc . How can i do that by c# desktop application?

Jørgen R
  • 10,568
  • 7
  • 42
  • 59
Red Swan
  • 15,157
  • 43
  • 156
  • 238

4 Answers4

6

try this:

List<string> mediaExtensions = new List<string>{"mp3", "mp4"};
List<string> filesFound = new List<string>();

void DirSearch(string sDir) 
{
   foreach (string d in Directory.GetDirectories(sDir)) 
   {
    foreach (string f in Directory.GetFiles(d, "*.*")) 
    {
        if(mediaExtensions.Contains(Path.GetExtension(f).ToLower()))
           filesFound.Add(f);
    }
    DirSearch(d);
   }
}
Manu
  • 28,753
  • 28
  • 75
  • 83
  • `Path.GetExtension()` returns extension with the dot separator prefixed `.`, so for the above code to work in the latest .NET versions, probably you should have there `if (mediaExtensions.Contains(Path.GetExtension(f).ToLower().Replace(".", "")))` – Alex P. Jan 21 '22 at 09:53
3

Rather than a brute-force iterative search through directories, I recommend looking into using the Windows Desktop Search API, which will be orders of magnitude faster.

Windows Desktop Search via C#

Community
  • 1
  • 1
richardtallent
  • 34,724
  • 14
  • 83
  • 123
0

To get your drive list:

string[] drives = Environment.GetLogicalDrives();

To get all your files:

foreach(string drive in drives)
    string[] allFiles = Directory.GetFiles(drive, "*.*", SearchOption.AllDirectories);

To get all your files using recursion:

List<string> allFiles = new List<string>();
private void RecursiveSearch(string dir)
{
    allFiles.Add(Directory.GetFiles(dir));
    foreach(string d in Directory.GetDirectories(dir))
    {
      RecursiveSearch(d);
    }  
}

Filter using Manu's answer

Amsakanna
  • 12,254
  • 8
  • 46
  • 58
0

try this

 var files = new List<string>();
     //@Stan R. suggested an improvement to handle floppy drives...
     //foreach (DriveInfo d in DriveInfo.GetDrives())
     foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
     {
        files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "File Name", SearchOption.AllDirectories));
     }
Tanmay Nehete
  • 2,138
  • 4
  • 31
  • 42