[英]A quick way to search for file extensions in C#
我正在尋找一種快速搜索特定文件擴展名的方法。 我嘗試了一種遞歸方法,但是遍歷計算機上的所有目錄花費的時間太長。 我找到了一種方法,可以通過在文件瀏覽器中輸入* .ISO來搜索帶有文件擴展名的所有文件,因此可以將這些結果復制到C#中。 我也歡迎其他任何以相似速度產生相同結果的方法。 稍后我還將需要同時搜索多個文件擴展名。
這是我嘗試的遞歸代碼。
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;
}
最快的是:
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();
之后,您可以使用\\n
分割輸出
這告訴您要搜索目錄+所有子目錄中的所有ISO文件,並僅給出路徑+文件名。
您還可以使用:
Directory.GetFiles(@"c:\", "*.iso", SearchOption.AllDirectories)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.