[英]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#. 我找到了一种方法,可以通过在文件浏览器中输入* .ISO来搜索带有文件扩展名的所有文件,因此可以将这些结果复制到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
之后,您可以使用\\n
分割输出
This is telling to search all ISO files in directory+all sub-directories and give only path+files names. 这告诉您要搜索目录+所有子目录中的所有ISO文件,并仅给出路径+文件名。
You can also use: 您还可以使用:
Directory.GetFiles(@"c:\", "*.iso", SearchOption.AllDirectories)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.