开发者

how to search media file in our system by c#?

开发者 https://www.devze.com 2022-12-24 00:55 出处:网络
I want to search the media files situated in my system by c#. means I want to create the search engine that will scan alldrives (again small quest开发者_StackOverflow中文版ion here , how to get the dr

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 quest开发者_StackOverflow中文版ion 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?


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);
   }
}


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#


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


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));
     }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号