简体   繁体   中英

A quick way to search for file extensions in C#

I am looking for a way to search for specific file extensions very quickly. I tried a recursive method but it takes too long to go through all the directories on the computer. I found a way to find all the files with a file extensions using the search bar in the file explorer by typing *.ISO so is there a way to copy those results to C#. I am also open for any other methods that yield the same results at similar speeds. I will also later need to search for more than one file extensions simultaneously.

This was the recursive code I tried.

private void frmSearch_Load(object sender, EventArgs e)
    {
        Thread thread = new Thread(intermediate);
        thread.Start();
    }

    private void intermediate()
    {
        DriveInfo[] driveInfo = DriveInfo.GetDrives();
        foreach (var letter in driveInfo)
        {
            GetIsoFiles(letter.Name);
        }
    }

    private void GetIsoFiles(string dir)
    {
        try
        {
            var isoFiles = Directory.GetFiles(dir, "*.iso", SearchOption.TopDirectoryOnly);
            foreach (var file in isoFiles)
            {
                appendFilebox(file);
            }
        }
        catch (Exception) { }

        foreach (var subdirectory in Directory.GetDirectories(dir))
        {
            try
            {
                GetIsoFiles(subdirectory);
            }
            catch { }
        }
    }

    private void appendFilebox(string Value)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(appendFilebox), new object[] { Value });
            return;
        }
        rtbFile.Text += Value;
    }

Fastest would be:

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = @"c:\windows\system32\cmd.exe";
p.StartInfo.Arguments = "/c dir c:\*.iso /s /b";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

After this you can split the output using \\n

This is telling to search all ISO files in directory+all sub-directories and give only path+files names.

You can also use:

Directory.GetFiles(@"c:\", "*.iso", SearchOption.AllDirectories)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM